summation of matrix in column

조회 수: 3 (최근 30일)
Khairul Nur
Khairul Nur 2019년 11월 25일
댓글: Andrei Bobrov 2019년 11월 26일
hi, i have this final_mat (40x11), below is my code. What i trying to do is,first it will check the value of j:1 equal to j (1,2,3,4). If true, i need to sum between column in the same value of j. I tried few times but end up summation of row . and tried again until..this is my last code since fews time since morning :(
Please give me some idea how to solve this.
example of final_mat:
1 13 25 15 11 11 14 12 12 10 14
1 14 25 15 11 11 14 12 12 10 10
sum 27 50 30 22 22 28 24 24 20 24
2 13 26 14 11 11 14 12 12 13 13
2 13 25 14 12 11 14 12 12 13 13
2 13 25 14 11 11 14 12 13 13 13
3 13 24 14 11 11 14 12 12 12 14
3 13 24 14 10 11 14 12 12 13 14
for n= 1:40
for j=1:4
if final_mat(j:1)==j
for jj=2:11
sum=sum+final_mat(:,jj) % stuck here.
end
end

채택된 답변

Andrei Bobrov
Andrei Bobrov 2019년 11월 25일
편집: Andrei Bobrov 2019년 11월 25일
final_mat = [ 1 13 25 15 11 11 14 12 12 10 14
1 14 25 15 11 11 14 12 12 10 10
2 13 26 14 11 11 14 12 12 13 13
2 13 25 14 12 11 14 12 12 13 13
2 13 25 14 11 11 14 12 13 13 13
3 13 24 14 11 11 14 12 12 12 14
3 13 24 14 10 11 14 12 12 13 14];
out = varfun(@sum,array2table(final_mat),'GroupingVariables',1)
out = out{:,[1,3:end]};
or
[i,j] = ndgrid(final_mat(:,1),1:size(final_mat,2));
out = accumarray([i(:),j(:)],final_mat(:),[],@sum);
out(:,1) = unique(final_mat(:,1));
  댓글 수: 2
Khairul Nur
Khairul Nur 2019년 11월 26일
its run perfectly! BTW can u explain more on the code, please..
for below code, use the varfun(func,A,'GroupingVariables','Var1') use the group count.
out = varfun(@sum,array2table(final_mat),'GroupingVariables',1)
how about this one?
out = out{:,[1,3:end]};
TQ again for ur time an helpful code.
Andrei Bobrov
Andrei Bobrov 2019년 11월 26일
Please read about 'Name-Value Pair Argument' - 'GroupingVariable' - may be name of variable (name of column of table) or number of column of table.

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

추가 답변 (0개)

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by