MATLAB: How to obtain total sum by group

accumarraytotal sum by group

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

Best Answer

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);