Finding sum of all the elements in a row corresponding to an element which is less than a certain value?

1 visualización (últimos 30 días)
I have a matrix which looks like this:
[1 0 3; 9 1 5; 6 0 9; 2 4 6; 5 2 0]
I want to find the sum of all the elements in column 2 and 3 if the corresponding element in column 1 is less than 3. For example: In column 1, 1 and 2 are less than 3 so the result should be the sum of all the rest of the elements of rows corresponding to 1 and 2 and the answer should be (0+3+4+6)=13. How can I do that in Matlab 2016a?

Respuesta aceptada

Alexandra Harkai
Alexandra Harkai el 21 de Nov. de 2016
Editada: Alexandra Harkai el 21 de Nov. de 2016
a = [1 0 3; 9 1 5; 6 0 9; 2 4 6; 5 2 0];
sum(sum( a(a(:,1)<3, 2:3) ))
a(:,1)<3 created a binary vector to indicate which rows satisfy the condition, a(a(:,1)<3, 2:3) creates the resulting array of elements to sum, then sum(sum()) adds up the results in both directions.

Más respuestas (0)

Categorías

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

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by