Cumulative sum by group

Asked by zppine on 27 Jul 2012
Latest activity Answered by zppine on 27 Jul 2012

Hi, Could someone explain how to compute the running sum by group (without using for loop)? A example is: groupid = [1; 1; 1; 2; 2; 3; 3;]; value=[1;2;3;4;5;6;7]. the desired result is: runsum = [1;3;6; 4;9; 6;13]. Thanks a lot. zppine

0 Comments

zppine

Products

No products are associated with this question.

2 Answers

Answer by Sean de Wolski on 27 Jul 2012
Edited by Sean de Wolski on 27 Jul 2012

Using a for-loop here may be your best option. However, my unconditional love for accumarray forces me to present you with this:

groupid = [1; 1; 1; 2; 2; 3; 3;]; 
value=[1;2;3;4;5;6;7]; 
gcs = cell2mat(accumarray(groupid,value,[],@(x){cumsum(x)}))

0 Comments

Sean de Wolski
Answer by zppine on 27 Jul 2012

Hi, Sean. Very good idea. Thanks a lot.

0 Comments

zppine

Contact us