Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if statement with 'or' operator gives different results when conditions are swapped

I'm using strfind with an 'or' comparison like so:

name='hello';
if strfind(name,'hello') | strfind(name,'hi')
    disp('yes!')
end

>> yes!

The if statement must evaluate as true, since yes! is displayed.

In contrast, MATLAB doesn't return yes! if the statements are swapped:

if strfind(name,'hi') | strfind(name,'hello')
    disp('yes!')
end

Why?

like image 946
Michaël Avatar asked Jan 29 '23 04:01

Michaël


1 Answers

This is because short-circuiting. Short-circuited logical operators are a thing to speed up code. You can have

if veryShort | superlongComputation

so what MATLAB does is first evaluate veryShort and if it is true, then no need to evaluate the second one! The if condition is already met.

In your case strfind(name,'hello') returns 1, but strfind(name,'hi') returns [].

In the first example, as the first thing evaluated returns 1, you get to the display. However in the second case, it returns [], therefore MATLAB evaluates the second thing in the if, and returns 1. Then MATLAB applies the or operations where [] | 1 is an 0x0 empty logical array, so the if is not true.

Note, generally you want to use || to enforce short-circuiting, but | also does it, if it is inside a while or an if:

https://uk.mathworks.com/matlabcentral/answers/99518-is-the-logical-operator-in-matlab-a-short-circuit-operator

like image 184
Ander Biguri Avatar answered Feb 05 '23 15:02

Ander Biguri