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

 채택된 답변

Geoff Hayes
Geoff Hayes 2015년 12월 18일

1 개 추천

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

Siying Liu
Siying Liu 2015년 12월 18일
Thank you very much! I did know how to obtain groupSums, but I didn't know how to expand that according to the groupid. The last line of the code is very clean and helpful!
Siying Liu
Siying Liu 2015년 12월 22일
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 2015년 12월 22일
Which is the matrix: the group ids or values, or both? Please provide an example.

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

jgg
jgg 2015년 12월 18일

1 개 추천

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 2015년 12월 18일

0 개 추천

group_sum = accumarray(groupid, value);
runsum = group_sum(A);

댓글 수: 1

Siying Liu
Siying Liu 2015년 12월 18일
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!

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

질문:

2015년 12월 18일

댓글:

2015년 12월 22일

Community Treasure Hunt

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

Start Hunting!

Translated by