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

8 Ansichten (letzte 30 Tage)
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

Akzeptierte Antwort

Star Strider
Star Strider am 2 Mär. 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 Kommentare
Johan
Johan am 4 Mär. 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 am 4 Mär. 2022
Thanks a lot for your solution @Johan Pelloux-Prayer!! It is very interesting! :)
(I would accept all the answers/solutions :) )

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Sim
Sim am 2 Mär. 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

Kategorien

Mehr zu Numeric Types finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by