SIMEL
SIMEL

Reputation: 8941

Unable to add a condition to a while loop in Matlab

I have a while loop which looks like this:

while ((min_t_border>0) && (colided_border_num > 0) && (~(min_t>0)))
    ...
end

I want to add to it another condition: (exit_border_point ~= false) or (exit_border_point) when I put ether of the conditions above in an if statement it works. But when I try to add it as an additional condition to the while, or even when I try to add another condition to the if, for example I've tried if ((exit_border_point ~= false) && (true)) it tells me:

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

What am I doing wrong?

*exit_border_point gets ether a (3x1) vector or false

Upvotes: 1

Views: 4996

Answers (3)

user664303
user664303

Reputation: 2063

If exit_border_point is a 3x1 vector then (exit_border_point ~= false) also returns a 3x1 vector, hence the error. Use this condition instead:

~isequal(exit_border_point, false)

Upvotes: 1

Elliot Cameron
Elliot Cameron

Reputation: 5297

Since exit_border_point can be a vector, try using the any or all functions, like this:

if (~any(exit_border_point))

As you can probably guess, any returns true if anything in the array evaluates to true and all returns true if everything in the array is true. They're kind of like vector equivalents to || and &&.

Upvotes: 2

Jonas
Jonas

Reputation: 74940

For the condition to make sense in the context of an if or while statement, it should evaluate to a scalar.

Thus, you should write

all(exit_border_point)

(which is equivalent to all(exit_border_point == true)), if you want true if all are true. Replace all with any if you want to exit the while-loop as soon as any exit_border_point is true.

Note that && and || only work for scalars. They're short-cut operators in that the second statement won't be evaluated if the first one determines the outcome (e.g. evaluates to false in case of &&. If you want to element-wise compare arrays, use & and |.

Upvotes: 1

Related Questions