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

1 次查看(过去 30 天)
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
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
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