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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With