Finding sum of all the elements in a row corresponding to an element which is less than a certain value?
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Mohammad Zaved Siddiqui
am 21 Nov. 2016
Kommentiert: Mohammad Zaved Siddiqui
am 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?
0 Kommentare
Akzeptierte Antwort
Alexandra Harkai
am 21 Nov. 2016
Bearbeitet: Alexandra Harkai
am 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.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Logical finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!