How to obtain total sum by group
35 次查看(过去 30 天)
显示 更早的评论
Hi, Could someone explain how to compute the total sum by group (without using for loop)?
A example is: groupid = [1; 1; 1; 2; 2; 3; 3;3]; value=[1;2;3;4;5;6;7;8]. the desired result is: runsum = [6;6;6;9;9; 21;21;21].
I am trying to get the result without using loop. Can "accumarray" do this?
Thanks a lot
Siying
0 个评论
采纳的回答
Geoff Hayes
2015-12-18
Siying - yes, accumarray can be used to sum elements of the same group. For example, we can do
groupSums = accumarray(groupid,value);
which gives us
groupSums =
6
9
21
with your runsum as
runsum = groupSums(groupid);
3 个评论
Geoff Hayes
2015-12-22
Which is the matrix: the group ids or values, or both? Please provide an example.
更多回答(2 个)
jgg
2015-12-18
Yes. This should work; it's probably not the shortest way to do it, but it avoids looping.
key = unique(groupid);
tsum = accumarray(groupid,value);
[~,idx] = ismember(groupid,key);
runsum = tsum(idx);
0 个评论
Walter Roberson
2015-12-18
group_sum = accumarray(groupid, value);
runsum = group_sum(A);
Your question reminds me of the similar http://uk.mathworks.com/matlabcentral/answers/260501-unique-and-min-by-index
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Entering Commands 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!