summation of matrix in column

1 次查看(过去 30 天)
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