How to manipulate in matrix
4 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Assume matrix i:
i = [
10010 8
10010 5
10010 2
10065 8
10065 6
10099 4
10099 2
10099 9
10099 4
10099 1
];
The first column is ID. There are three different IDs and repeated for 10 rows. I want to sum the second column corresponding to each ID as follows:
j = [
10010 15
10010 15
10010 15
10065 14
10065 14
10099 20
10099 20
10099 20
10099 20
10099 20
];
3 comentarios
Guillaume
el 22 de Mayo de 2017
How can I accept an answer?
By clicking on the big blue button that says "Accept this answer" above the answer you want to accept.
Respuestas (3)
Image Analyst
el 22 de Mayo de 2017
Sounds like it might be homework. Here's a start. See if you can finish it.
out = accumarray(i(:, 1), i(:, 2));
out(out==0) = []
Returns [15;14;20]
Akira Agata
el 25 de Mayo de 2017
How about using splitapply function.
A = [
10010 8
10010 5
10010 2
10065 8
10065 6
10099 4
10099 2
10099 9
10099 4
10099 1
];
[G, ID] = findgroups(A(:,1));
B = [ID, splitapply(@sum,A(:,2),G)];
Now, the output matrix B is as follows:
B =
10010 15
10065 14
10099 20
0 comentarios
Andrei Bobrov
el 25 de Mayo de 2017
[~,~,c] = unique(ii(:,1));
D = accumarray(c,ii(:,2));
out = [ii(:,1), D(c)];
0 comentarios
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!