Filter löschen
Filter löschen

How to obtain total sum by group

35 Ansichten (letzte 30 Tage)
Siying Liu
Siying Liu am 18 Dez. 2015
Kommentiert: Geoff Hayes am 22 Dez. 2015
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

Akzeptierte Antwort

Geoff Hayes
Geoff Hayes am 18 Dez. 2015
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 Kommentare
Siying Liu
Siying Liu am 22 Dez. 2015
I have one more following up question. The last line seems to work only if the groupSums is a vector, is there a way I can expand this method to a matrix? Thank you in advance!
Geoff Hayes
Geoff Hayes am 22 Dez. 2015
Which is the matrix: the group ids or values, or both? Please provide an example.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (2)

jgg
jgg am 18 Dez. 2015
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);

Walter Roberson
Walter Roberson am 18 Dez. 2015
group_sum = accumarray(groupid, value);
runsum = group_sum(A);
  1 Kommentar
Siying Liu
Siying Liu am 18 Dez. 2015
Yes! I did read that thread! The problem I have is don't know how to covert the group sum to the matrix I need without using a loop.
Thanks!

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Entering Commands finden Sie in Help Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by