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

조회 수: 8 (최근 30일)
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

채택된 답변

Star Strider
Star Strider 2022년 3월 2일
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
Johan
Johan 2022년 3월 4일
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 2022년 3월 4일
Thanks a lot for your solution @Johan Pelloux-Prayer!! It is very interesting! :)
(I would accept all the answers/solutions :) )

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Sim
Sim 2022년 3월 2일
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

카테고리

Help CenterFile Exchange에서 Numeric Types에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by