Sum elements in the first column according to repeated values in a second column

11 views (last 30 days)
Hi, I have a two columns matrix, where the elements of the second column are repeated (here below in my example, 55, 98 and 17 are repeated several times).
I would like to sum the elements of the first column, which have (in common) the same element of the second column. Here an example... any fast way to do it?
% Input
A = [ 4 55
3 55
7 55
1 55
9 98
1 98
2 98
8 98
0 98
1 98
6 17
3 17
0 17
4 17]
% desired output
B = [15 55
21 98
13 17];
where, for example, the value 15 in B(1,1) is given by 4 + 3 + 7 + 1 = 15

Accepted Answer

Star Strider
Star Strider on 2 Mar 2022
A = [ 4 55
3 55
7 55
1 55
9 98
1 98
2 98
8 98
0 98
1 98
6 17
3 17
0 17
4 17];
[A2u,~,ix] = unique(A(:,2));
A1sums = accumarray(ix,A(:,1),[],@sum);
Desired_Result = [A1sums A2u]
Desired_Result = 3×2
13 17 15 55 21 98
The loops are still there, however they are hidden inside the accumarray call.
.
  4 Comments
Johan
Johan on 4 Mar 2022
I figured a pretty obfuscated way to do that without for loop; note that it's slower than using accumarray :)
A = [ 4 55
3 55
7 55
1 55
9 98
1 98
2 98
8 98
0 98
1 98
6 17
3 17
0 17
4 17];
logicalmask = A(:,2) == unique(A(:,2))';
result = [sum(A(:,1).*logicalmask)',unique(A(:,2))]
result = 3×2
13 17 15 55 21 98
Sim
Sim on 4 Mar 2022
Thanks a lot for your solution @Johan Pelloux-Prayer!! It is very interesting! :)
(I would accept all the answers/solutions :) )

Sign in to comment.

More Answers (1)

Sim
Sim on 2 Mar 2022
I found this solution, but I would like to avoid the loop for:
[a,b] = unique(A(:,2));
[~,d] = unique(A(:,2),'last');
for i = 1 : size(a,1)
B1(i) = sum(A(b(i):d(i),1));
end
B = [B1' a]
% result
B =
13 17
15 55
21 98

Categories

Find more on Numeric Types in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!