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
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
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 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

产品


版本

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by