sum matrix by group using logical operators and "if"
Show older comments
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
More Answers (0)
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!