summation of matrix in column

1 回表示 (過去 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 Center および File ExchangeMathematics についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by