I would like to sum a 2 dim array group by value in second column
2 次查看(过去 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
0 个评论
回答(1 个)
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)]
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)
2 个评论
Abolfazl Chaman Motlagh
2022-6-18
Here's a one line solution :)
X = [rand(6,1),randi(4,6,1)]
Y = [sum((X(:,2) == unique(X(:,2))') .* repmat(X(:,1),1,numel(unique(X(:,2)))))' , unique(X(:,2))]
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!