Skip to Main Content Skip to Search
File Exchange
MATLAB Newsgroup
Link Exchange
  Blogs  
 Contest 
MathWorks.com

Loren on the Art of MATLAB

November 2nd, 2006

Bottom Line on Logical

I just posted a blog on logical operator behavior in MATLAB and I want to be clear about the bottom line.

Use the newer MATLAB operators || and &&, in the context of expressions for if and while. The newer operators always short-circuit, not just in if and while expressions. The newer operators force you to be clear about your intention with respect to matrix expressions (including empty ones) and you choose how to reduce the array expressions to scalar ones that are unambiguous.

7 Responses to “Bottom Line on Logical”

  1. Dan K replied on :

    Um, that seems a little to generalized of a statement to me. Using & and | is the only way to do logical indexing, isn’t it? I often use those tests for cases such as:

    data=rand(100,1);
    middleHalf=data(data>0.25 & data

  2. Loren replied on :

    Dan-

    Thanks for pointing this out. I was thinking about if and while so I went back and made that more explicit.

    –Loren

  3. Oliver A. Chapman, PE replied on :

    A few of us looked at this for a while yesterday and we think the short circuiting in the “or” operator isn’t operating properly. Or, at least isn’t operating as we expect.

    Here are some commands and comments to illustrate:

    First, rationally, the “or” operator should operate on logical variables. But, clearly it is an advantage if MatLab can convert from other data types to logical within the arguments of the operator. So, a question we asked was, how does MatLab convert doubles to logicals?

    logical(4)

    ans =

    1

    This makes sense and is what we expect.

    Now a slightly harder situation, converting an empty double to logical.

    >> logical([])

    ans =

    []

    >> isempty([])

    ans =

    1

    This makes sense, an empty double gets converted to an empty logical.

    Now, how does the “or” operator deal with different sizes of variables:

    >> (1:5)|(1:4)
    ??? Error using ==> or
    Inputs must have the same size.

    How about if one is empty?

    >> (1:5)|([])
    ??? Error using ==> or
    Inputs must have the same size.

    That makes sense because the empty variable has size zero.

    >> size([])

    ans =

    0 0

    With this background, the expected response within the “if” statement would be the same error message.

    Further, it certainly doesn’t make sense for the “or” operator to short circuit to false when the first variable is false. Although this makes sense for an “and” operator, doesn’t the “or” operator always have to test both?

  4. Loren replied on :

    Oliver-

    You are missing the part about scalar expansion that works with many operators in MATLAB, including +, |, &. If I say

    x = 1:3
    y = []
    x+y
    

    I get the error message about matrix dimensions must agree, but I don’t if x = 3. In that case, MATLAB does a scalar expansion and I get the scalar to expand to the size 0×0 and therefore, I get an empty result.

    The same thing is happening with

    if [] | 4
      whatever
    end
    

    MATLAB can’t tell from the first part of the expression if the entire expression is true yet, so it keeps going. Then MATLAB computes [] | 4, using scalar expansion, empty is returned as the final expression for the if statement, and the result is then treated as false.

    –Loren

  5. Oliver A. Chapman, PE replied on :

    Loren,

    I think that MatLab has made this sufficiently complex.

    Let’s go back to the “or” operator.

    >> []|4

    ans =

    []

    >> 4|[]

    ans =

    []

    As expected, I get the empty result, regardless of order of the inputs.

    But, there is no rational justification for the different result if imbedded in an if or while statement.

    >> if []|4
    disp(’true’);
    else
    disp(’false’);
    end;
    false

    >> if 4|[]
    disp(’true’);
    else
    disp(’false’);
    end;
    true
    >>

    What does the specification for the MatLab “if” statement say regarding this feature?

    Or, was the “if” statement written without a specification?

  6. Steve Eddins replied on :

    Oliver - I understand your consternation about this behavior. Believe me, you are not alone. But there’s no reason for your suggestion of a lack of a spec. In fact, the behavior is completely documented. (See Documentation -> MATLAB -> MATLAB Programming -> Logical Operators -> Short-Circuiting in Element-Wise Operators.)

    We cannot change this behavior now without breaking a great deal of existing customer code. So what we have done instead is to introduce the scalar, always-short-circuiting logical operators, and to encourage their use in if and while conditionals. The MATLAB Editor will even make this suggestion to you if you use “|” or “&” in an if or while conditional expression.

  7. Oliver A. Chapman, PE replied on :

    Steve & Loren,

    Certainly it is fair for you to defend the way MatLab operates. And, you are correct regarding the documentation of the “if” statement.

    Even though I continue to lobby MatLab for specific improvements in the documentation when I encounter deficiencies, the documentation for “if” is very good.

    However, for well designed software, the documentation serves as a backstop to its logical & reasonable operation. Further, in this case, the documentation of the “or” operator doesn’t give any hint to its different behavior when imbedded in an “if” statement.

    I stand by the point I made that none of us here think it is reasonable for the outcome for an “or” operation be order dependent.

    Further, I am more troubled by Steve’s comments regarding the specification for the “or” statement. A reasonable answer would be something like, “Yes MatLab’s specification for the “or” statement does discuss this behavior, but for proprietary reasons, we can’t share it with you.” Instead, he glosses over the issue with a “non-denial-denial.”

    In my first reply to this, on November 1, I assumed there was a performance benefit to this feature and asked for an example. No reply yet. Show us how these other customers have taken advantage of this feature.

    Reading between the lines, I suspect that this behavior kind of “happened” in the original version of MatLab and has recently been incorporated into the current specifications.

    Here is the bottom line: MatLab is an expensive bit of software that is well worth the price. It is generally very well designed and has outstanding documentation. Users can quickly engage with MatLab even when approaching it from varied backgrounds and perspectives.

    However, for the users like me and those around me, this feature that we’ve been discussing is not expected and Loren’s column is a good forum to discuss it. I read her column just so I can learn these details. Give some examples as I discuss above and then we’ll move on to other topics.

Leave a Reply


Loren Shure works on design of the MATLAB language at The MathWorks. She writes here about once a week on MATLAB programming and related topics.

  • Ulla Vainio: That error bar width adjustment was extremely useful and I would never have figured it out myself....
  • Peter Perkins: Jessee, there is a property that you can use to tag variables with units. For example, >> load...
  • Jessee: I could potentially see myself using dataset for casually looking at data, but from an application standpoint...
  • Loren: Oktay- It very much depends on the details of the calculations you are doing. Vectorization can sometimes...
  • Oktay: Hello, Is there any significant difference between using: - Vectorization inside a subfunction - Benefiting...
  • Loren: Clare- Yes, sum can sum a double vector: x = [.3 .4 pi/3] y = sum(x) x = 0.3 0.4 1.0472 y = 1.7472 You must...
  • Clare J: R2007a - Student Version When I use sum to sum a vector of type double I get this error message: ???...
  • Sarah Zaranek: Hi Jacob, Sorry about the slow response. You are correct that the code would be slower without the...
  • Navaneethan Santhanam: Thanks a lot, Loren! That worked perfectly.
  • Mike N: Should it be OK to use “persistent 221; variables in a deployed application? What if I have two...

These postings are the author's and don't necessarily represent the opinions of The MathWorks.

Related Topics