sum matrix by group using logical operators and "if"

조회 수: 2 (최근 30일)
Christine Fesler
Christine Fesler 2015년 11월 3일
편집: Nitin Khola 2015년 11월 5일
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.

채택된 답변

Nitin Khola
Nitin Khola 2015년 11월 5일
편집: Nitin Khola 2015년 11월 5일
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 (<http://www.mathworks.com/help/matlab/math/matrix-indexing.html#bq7eg38>) 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
ans
0.9817 0.4783 0.6146 0.1439
>> sum(M(M(:,5)==3,1:4))
ans =
2.2185
  댓글 수: 1
Christine Fesler
Christine Fesler 2015년 11월 5일
Hi, Thank you very much for the response. This is great!

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by