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

2 次查看(过去 30 天)
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?

采纳的回答

Alexandra Harkai
Alexandra Harkai 2016-11-21
编辑:Alexandra Harkai 2016-11-21
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.

更多回答(0 个)

类别

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

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by