sum matrix by group using logical operators and "if"
显示 更早的评论
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.
采纳的回答
更多回答(0 个)
类别
在 帮助中心 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!