Short-circuit logical operators in Matlab

A “feature” of the Matlab language, as mentioned in its document (at least until version 2010b), is that in the condition expression of an if or a while statement, the element-wise conjunction operator (&) and disjunction operator (|) ALWAYS use short-circuiting. Thus, if func is a function, the following code

if func(1) | func(2), do something; end

is not equivalent to the following code

cond = func(1) | func(2);
if cond, do something; end

Another example: while 1|[] evaluates to false in a statement, the exact same expression evaluates to true when used in an if or a while statement.

Personally, I think this “feature” of the Matlab language is unnecessary, even dangerous. It may cause bugs that are very difficult to find. And it causes inconsistency in the language because anywhere else the element-wise logical operators are not short-circuit and because short-circuit logical operations are already explicitly specified by operators like && and ||.

This “feature” should be removed from Matlab so that the above code fragments would produce the same result.

This entry was posted in Matlab and tagged . Bookmark the permalink.

One Response to Short-circuit logical operators in Matlab

  1. amit jaisal says:

    go through the mat lab document sometimes we require to remove dependancy on only one input in such cases it becomes essential .

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s