I just stumbled on another reason to dislike Matlab: the stupid inconsistency of the short-circuit behavior of the elementwise logical operators: the statement
fun(2) | fun(9999)
does not short-circuit, so both fun(2)
and fun(9999)
are executed,
but when used in an if
or while
expression like
if fun(2) | fun(9999); end;
the expression does short-circuit, meaning that only fun(2)
is executed.
I know, you also have the ||
and &&
operators, which are defined as short circuiting operators, but the inconsistency with the |
and &
operators is just stupid, if not evil.
For example, say that function fun(x)
is defined as
function y = fun(x)
disp(sprintf(' --> called fun(%d)', x));
y = x;
end
and we execute the script
disp('fun(2) | fun(9999);')
fun(2) | fun(9999);
disp('if fun(2) | fun(9999); end;')
if fun(2) | fun(9999); end;
disp('fun(2) || fun(9999);')
fun(2) || fun(9999);
disp('if fun(2) || fun(9999); end;')
if fun(2) || fun(9999); end;
In Matlab (R2007a), I get:
fun(2) | fun(9999);
--> called fun(2)
--> called fun(9999)
if fun(2) | fun(9999); end;
--> called fun(2)
fun(2) || fun(9999);
--> called fun(2)
if fun(2) || fun(9999); end;
--> called fun(2)
See? With the first |
-statement, there are two fun()
calls and with the second |
-statement, there is only one. And they even dare to call this a feature in the Matlab documentation. Another proof that Matlab is a horrible programming environment.
Funnily, the open source Matlab-replacement Octave gets it right and shows consistency:
fun(2) | fun(9999);
--> called fun(2)
--> called fun(9999)
if fun(2) | fun(9999); end;
--> called fun(2)
--> called fun(9999)
fun(2) || fun(9999);
--> called fun(2)
if fun(2) || fun(9999); end;
--> called fun(2)
Anyway, I'm happy I decided to leave Matlab (unless forced to use it) and switched to Python+Scipy.