sum matrix by group using logical operators and "if"

7 views (last 30 days)
Hi, I am having trouble figuring out how to use the "sum" function for a (480,11) data matrix that is conditional on a numerical group id that is a(480,1) matrix where group ids are 1-10. I know the sum function of a matrix creates a (1xn) row output with the sums of the columns. I want the output of the sum by groups to be placed in a (10,11) matrix where row 1 = sum of group id 1,...,row 10 = sum of group id 10. I have tried to use a logical operator such that: Total = zeros(10,11); for n = 1:length(groupid); if groupid(n,:)==1; Total(1,:) = sum(data); elseif groupid(n,:)==2; Total(2,:) = sum(data); . . . else Total(10,:) = sum(data); end end
This code only results in summing the all columns regardless of the group id. I have used dummyvar function to create new variables; however, this tends to clutter the workspace and I thought there must be some way to use a logical operator with the sum function.

Accepted Answer

Nitin Khola
Nitin Khola on 5 Nov 2015
Edited: Nitin Khola on 5 Nov 2015
As you mentioned towards the end of your question, you can append to your original data matrix, another column of group IDs and use logical indexing. So your new matrix is of size 480X12. Let's call it "M". Now, you can use logical indexing (<>) to sum up all the values corresponding to a particular group ID.
To illustrate this idea, here is an example code:
>> groupID = [3; 2; 1; 4];
>> originalData = rand(4);
>> M = [originalData groupID]; % concatenate the two matrices
>> M
M =
0.9817 0.4783 0.6146 0.1439 3.0000
0.5676 0.0863 0.4986 0.4151 2.0000
0.1876 0.0747 0.3407 0.5796 1.0000
0.4215 0.2468 0.0071 0.7520 4.0000
>> M(M(:,5)==3,1:4) % Index into the row with a group ID of 3
0.9817 0.4783 0.6146 0.1439
>> sum(M(M(:,5)==3,1:4))
ans =
  1 Comment
Christine Fesler
Christine Fesler on 5 Nov 2015
Hi, Thank you very much for the response. This is great!

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!