Order of values ​​in a boolean expression in if-clause

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

leads to 1 | [] 1 | [] . The first is executed, if executed.

How is this behavior? I would suggest that both have the same result.

+6
source share
2 answers

I would say that this is most likely an error caused by the interpreter, although MathWorks may claim this behavior is undefined.

On the command line, cond1 = 1|[]; and cond2 = []|1; evaluated to [] because all operations with [] return [] . Since [] evaluates to false if used in the condition, so you can expect both cases to behave the same if they are used in the if condition.

In addition to the logical operators of the array, Matlab also offers short-circuit operators where the evaluation of conditions is stopped if the result is clear from considering only parts of the condition. Evaluated on the command line, the massive operation 1|[] returns [] , and 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 should ever evaluate them.

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

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

+4
source

Because Matlab interprets logical operations in if statements only when the result depends on it. Interpretation 1 | X 1 | X usually true regardless of the second expression, so the interpreter will accept the shortcut (erroneously in the case of X = [] .
[] | X [] | X is false no matter what the second expression is, so the result is false.

+1
source

Source: https://habr.com/ru/post/986560/


All Articles