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.
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.
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.
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