How to manipulate in matrix

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 commentaires

the cyclist
the cyclist le 22 Mai 2017
Zhan, you have now asked 10 questions on this forum, many of which have correct answers. You have not accepted any answers yet (at least as I write this). So, those of us who have answered your questions have no way of knowing if we have been helpful, and are losing incentive to provide you with more answers.
Zhan
Zhan le 22 Mai 2017
@the cyclist Thank you for your comment. How can I accept an answer?
Guillaume
Guillaume le 22 Mai 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.

Connectez-vous pour commenter.

Réponses (3)

Image Analyst
Image Analyst le 22 Mai 2017

0 votes

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]

1 commentaire

Zhan
Zhan le 22 Mai 2017
out = out(i(:,1),:)
% works if IDs are [1,1,1,2,2,3,3,3,3,3]. Any tips for the oroginal ID?

Connectez-vous pour commenter.

Akira Agata
Akira Agata le 25 Mai 2017

0 votes

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
Andrei Bobrov
Andrei Bobrov le 25 Mai 2017

0 votes

[~,~,c] = unique(ii(:,1));
D = accumarray(c,ii(:,2));
out = [ii(:,1), D(c)];

Catégories

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by