Lucas
Lucas

Reputation: 14129

How to check in MATLAB if a vector only contains zeros?

What is the "MATLAB-way" to check if a vector only contains zeros, so that it will be evaluated to a scalar rather than to a vector. If I run this code:

vector = zeros(1,10)

%the "1" represents a function that returns a scalar
if 1 && vector == 0   %this comparision won't work
    'success'
end

I get the error:

??? Operands to the || and && operators must be convertible to logical scalar values.

Upvotes: 14

Views: 33929

Answers (5)

James Mertz
James Mertz

Reputation: 8759

You can also do it using this:

if(boolFunCall() & ~vector)
    disp('True');  
else
    disp('False');
end

Just as Doresoom stated, your problem is in the use of && instead of &. Also, the ~ inverts all of the 1's and 0's thereby making a zero vector into a vector of 1's:

test = [0 0 0 0 0 0];
~test
ans =

     1     1     1     1     1     1     1
test = [1 0 0 1 0 1 0 0 0];
~test
ans =

     0     1     1     0     1     0     1     1     1

Upvotes: 0

Shai
Shai

Reputation: 114786

A bit late, but how about nnz (Number of Non-Zeros)?

if 1 && nnz(vector)==0
    'success'
end

Upvotes: 4

AnnaR
AnnaR

Reputation: 3186

You can easily find out if any and how many entries in vector contain non-zero elements using the following:

vector = zeros(1, 10); 
nrNonZero = sum(vector~=0)

vector~=0 returns an array of the same dimensions as vector containing zeros and ones, representing true and false, for the given statement. The variable nrNonZero then contains the number of non-zero elements in vector.

So, your code would then be

if (sum(vector~=0) == 0)
    'success'
end

Upvotes: 1

Richie Cotton
Richie Cotton

Reputation: 121057

Since zeros are treated the same way as false, you don't need to use vector == 0, as ptomato suggests. ~any(vector) is the "MATLAB-way" to check for only zero values.

if 1 && ~any(vector)   
    'success'
end

Extending the problem to arrays, you'd have to use

array = zeros(5);
if 1 && ~any(array(:))
    'success'
end

Upvotes: 15

ptomato
ptomato

Reputation: 57854

Use all:

vector = zeros(1,10)
if 1 && all(vector == 0)   %this comparision will work
    'success'
end

Upvotes: 24

Related Questions