Sum the values of an matrix
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentar
Adam Danz
am 5 Aug. 2019
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.
Akzeptierte Antwort
Adam Danz
am 5 Aug. 2019
Bearbeitet: Adam Danz
am 5 Aug. 2019
% 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 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!