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

3 views (last 30 days)
Mohammad Zaved Siddiqui on 21 Nov 2016
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 on 21 Nov 2016
Edited: Alexandra Harkai on 21 Nov 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.
Mohammad Zaved Siddiqui on 21 Nov 2016
Work perfectly. Thanks :)

### Categories

Find more on Logical in Help Center and File Exchange

### Community Treasure Hunt

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

Start Hunting!