Sum the values of an matrix
2 ビュー (過去 30 日間)
古いコメントを表示
Hi ,
given a matrix
SU = [1 0 1 0 1 0 1 1 1 0 1 0 0;
0 0 0 1 1 0 0 1 0 1 0 0 0;
1 1 1 0 0 0 0 0 1 1 1 0 0]
I want to assign the value 6 to all the 1 of the first raw, 3 to all the 1 of the second raw, 2 to all the 1 of the third raw. Obtaining:
SU = [6 0 6 0 6 0 6 6 6 0 6 0 0;
0 0 0 3 3 0 0 3 0 3 0 0 0;
2 2 2 0 0 0 0 0 2 2 2 0 0]
Then I want to create a vector B that contain the sum of all the column. for example, the first element of B should be equal to 6+0+2=8. Obtaining
B = [8 2 8 3 9 0 6 9 8 5 8 0 0]
Does someone help me to write this code?
Thanks
1 件のコメント
Adam Danz
2019 年 8 月 5 日
1) SU is a matrix, not a vector.
2) I think you meant to assign a value of 2 to the third column, not 3, based on the B summation.
採用された回答
Adam Danz
2019 年 8 月 5 日
編集済み: Adam Danz
2019 年 8 月 5 日
% SU Matrix
SU = [1 0 1 0 1 0 1 1 1 0 1 0 0;
0 0 0 1 1 0 0 1 0 1 0 0 0;
1 1 1 0 0 0 0 0 1 1 1 0 0];
% Replace 1 with 6,3,2 in 1st, 2nd, 3rd rows respectively
% This assumes all values in SU are either 1 or 0.
SU = SU .* [6;3;2];
% If the above assumption is incorrect use this line instead.
% SU = (SU==1) .* [6;3;2]
% Sum columns
B = sum(SU,1)
0 件のコメント
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Matrix Indexing についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!