1

I need some help please. Let's say I have a matrix:

   4 5 6 6
a= 2 7 9 1
   9 0 4 5

I want to find the sum of row 2, without including the minimum value of row 2 (that's 1), I have tried this:

sum(a(2,:)~=1)

but it does not work. Can someone help?

2 Answers 2

2

Another way to do this without indexing is to subtract the minimum off of the sum,

sum(a(2, :)) - min(a(2, :))
0

Your code

sum(a(2,:)~=1)

tells you how many entries in the second row are not the minimum of 1. That's because the argument to sum,

>> a(2,:)~=1
ans = 
     1     1     1     0

is a logical array that indicates whether each of the numbers in that row is different from 1, and the logical values false and true are interpreted as numbers 0 and 1 by sum.

What you want to do is use these values for logical indexing into the row, and summing only the selected elements

ind = a(2,:)~=1;
sum(a(2,ind))

or shorter

sum(a(2,a(2,:)~=1))

Of course for generality it would be better to replace 1 by the expression min(a(2,:))

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .