I would like to sum a 2 dim array group by value in second column

조회 수: 1 (최근 30일)
simon lumsdon
simon lumsdon 2022년 6월 18일
댓글: Abolfazl Chaman Motlagh 2022년 6월 18일
I have an nX2 array
0.1 5
0.3 5
0.34 2
0.4 3
0.1 5
-.9 1
-6 2
and want to sum the first column grouped by the second to create an nX2 array that looks like
-0.9 1
-5.66 2
.4 3
0.5 5
I am sure its simple but its giving me brain ache :-)
Many thanks

답변 (1개)

Abolfazl Chaman Motlagh
Abolfazl Chaman Motlagh 2022년 6월 18일
there are a lot of ways to do this, here's a simple solution. i would recommend you to understand every line and run it line by line. try writing this code vectorize, i mean without for loop :)
X = [rand(6,1),randi(4,6,1)]
X = 6×2
0.2612 2.0000 0.6470 3.0000 0.4749 4.0000 0.6048 3.0000 0.6482 1.0000 0.1296 2.0000
Y = unique(X(:,2));
Y(end,2)=0;
for i=1:size(X,1)
ind = X(i,2)==Y(:,1);
Y(ind,2) = Y(ind,2) + X(i,1);
end
Y = flip(Y,2)
Y = 4×2
0.6482 1.0000 0.3909 2.0000 1.2518 3.0000 0.4749 4.0000
  댓글 수: 2
simon lumsdon
simon lumsdon 2022년 6월 18일
Many thanks, it works perfectly. Wow, had rather hoped there was a single line solution to this type of problem, some form of sum, group by approch, hadnt expected to have to tackle it long hand. Not sure I have the skills to turn that into one line of code though?
Abolfazl Chaman Motlagh
Abolfazl Chaman Motlagh 2022년 6월 18일
Here's a one line solution :)
X = [rand(6,1),randi(4,6,1)]
X = 6×2
0.8407 1.0000 0.1779 4.0000 0.2698 1.0000 0.7353 4.0000 0.8105 1.0000 0.1059 3.0000
Y = [sum((X(:,2) == unique(X(:,2))') .* repmat(X(:,1),1,numel(unique(X(:,2)))))' , unique(X(:,2))]
Y = 3×2
1.9210 1.0000 0.1059 3.0000 0.9132 4.0000

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

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by