tags:

views:

133

answers:

2

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.

+8  A: 

Use all:

vector = zeros(1,10)
if 1 && all(vector == 0)   %this comparision will work
    'success'
end
ptomato
Perfect! That was quick.
Lucas
gnovice
@gnovice: I don't actually have `1` there, but a function that returns a scalar.
Lucas
gnovice
@gnovice: You are right. I edited my question, but don't want to remove the `1` or the answers will seem weird. If I don't have a logical operand though, the problem doesn't exist.
Lucas
+2  A: 

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
Richie Cotton
This is also neat. Thanks!
Lucas
gnovice

related questions