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

1 view (last 30 days)
simon lumsdon on 18 Jun 2022
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

Abolfazl Chaman Motlagh on 18 Jun 2022
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 CommentsShowHide 1 older comment
Abolfazl Chaman Motlagh on 18 Jun 2022
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