2

Why does the expression:

-5 < -3 < -1

evaluate to 0 in MATLAB? The separate statements each evaluate to true, so I'm confused as to why it's evaluating to false.

Many thanks.

1
  • 2
    you would need to break that into two comparisons if you intended to do a comparison of -3 to the other values (as in an inequality). Something like this (-5 < -3) && (-3 < -1) Dec 15, 2015 at 18:56

2 Answers 2

14

Because it really looks like this:

(-5 < -3) < -1

-5 < -3 is true, which is also 1.

1 < -1 is false, which is also 0.

Final answer: 0.

10

MATLAB operates left to right for the less than operator.

So you are evaluating

-5 < -3 < -1
TRUE < -1
FALSE
6
  • 1
    Haha. I was just about to delete my answer Dec 15, 2015 at 18:50
  • 3
    Nah leave it. This answer is good because you have linked to official documentation regarding the behaviour. The answer with the highest votes does this out of pure logic, but you've provided an official link of where this behaviour is documented in addition to explaining how the result is produced. I'd personally accept this answer if I was the OP.
    – rayryeng
    Dec 15, 2015 at 18:56
  • 1
    Psh, I don't care either way. I don't know the internals of MATLAB at all but boolean logic? That I know well. Most languages will have syntax errors with the -5 < -3 < -1 statement because they care that booleans can't be compared with integers, but in less strict languages a boolean TRUE is exactly the same as an integer 1 (any non-zero value evaluates to true, but true is explicitly stored as 1). So I immediately understood what was going on. The parens are also something that's always there. Even 5 + 3 + 2 is really (5 + 3) + 2 but we don't write them down. Dec 15, 2015 at 19:11
  • 2
    @Draco18s Actually, in Python, doing -5 < -3 < -1 is equivalent to doing -5 < -3 && -3 < -1, which will evaluate to True link - start at Comparisons can be chained arbitrarily.... We can't assume that this assumed behaviour is the same amongst all programming languages. That's why I prefer this answer as it linked to official documentation. FWIW, I did upvote your answer as it got to the point quickly but you can't assume from logic that your answer holds True for all programming languages.
    – rayryeng
    Dec 15, 2015 at 19:24
  • 1
    @Draco18s true, but some old notable languages are even worse. The fact is that in C, it is not defined whether -5 < -3 or -3 < -1 is evaluated first... Tough luck or something I guess. I would say it is good practice to have parathesis where they belong in case of operators with the same priority.
    – patrik
    Dec 16, 2015 at 7:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.