Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

order of values in logical expression in if-clause

Tags:

matlab

if 1 | []
    disp('1 | []');
end

if [] | 1
    disp('[] | 1');
end

results in 1 | []. The first if is executed.

How come this behaviour? I would assume both have the same result.

like image 637
Steffen Avatar asked May 05 '15 09:05

Steffen


2 Answers

I'd say that this is most likely a interpreter-induced bug, although MathWorks might claim it's undefined behavior.

On the command line, both cond1 = 1|[]; and cond2 = []|1; evaluate to [], because all operations involving [] return []. Since [] evaluates to false if used in a condition, one would therefore expect both cases to behave the same way if used in an if-clause.

Aside from the array-wise logical operators, Matlab also offers short-circuit operators, where the evaluation of conditions is stopped if the result is clear from looking at parts of the condition only. Evaluated on the command line, the array-wise operation 1|[] returns [], while the short-circuit operation 1||[] returns 1. Note that []||1 throws an error, since the short-circuit operator only works with scalar conditions, unless it never has to evaluate them.

So far, everything is as expected. What I suspect happens in our unexpected case is that the interpreter implicitly replaces 1|[] by 1||[] inside the if-clause, possibly because the operation starts with a scalar, and [] is not an array.

If at all possible, you should avoid calculating with [], and catch potential such cases with isempty.

like image 137
Jonas Avatar answered Nov 09 '22 10:11

Jonas


As Matlab interprets logical operations in if statements only when the result does depend on it. Interpreting 1 | X is usually true no matter what the second expression is, so the interpreter will take the shortcut (wrongly in case X = [].
[] | X is false no matter what the second expression is, so the result is false.

like image 24
wiseveri Avatar answered Nov 09 '22 09:11

wiseveri