Borrar filtros
Borrar filtros

Sum the values of an matrix

2 visualizaciones (últimos 30 días)
luca
luca el 5 de Ag. de 2019
Editada: luca el 5 de Ag. de 2019
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 comentario
Adam Danz
Adam Danz el 5 de Ag. de 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.

Iniciar sesión para comentar.

Respuesta aceptada

Adam Danz
Adam Danz el 5 de Ag. de 2019
Editada: Adam Danz el 5 de Ag. de 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)

Más respuestas (0)

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Productos


Versión

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by