MATLAB: Order of logical operators

MATLAB

1 < 5 > 2 gives false

Best Answer

You need to recognize how MATLAB evaluates a logical expression. Many people use that shorthand, to indicate two coupled comparisons. But MATLAB does not understand that as you do.
It sees the first expression, 1<5. The result is TRUE, represented as the number 1.
Then it compares that result to the number 2. Is 1 > 2? Of course not. So the result is false. Effectively, you can think of the expressions:
1 < 5 > 2
(1 < 5) > 2
as equivalent in the eyes of MATLAB.
So, IF you wanted to write the expression
(1 < 5) && (5 > 2)
then you need to write it as two separate comparisons, not in a shorthand, something that means what you want it to mean. In fact, the order of operations allows you to write the above pair of comparisons without parens, since || and && occupy a lower place in the operator precedence table. You can find the complete list here:
1 < 5 && 5 > 2
Personally, I always choose to use parens there, even though I know the two versions, with and without those parens are the same. It is easier to read, to know unequivocably what was intended when parens are employed. And since easy to read code is of paramount importance when you write code, I just use those parens, because I want to be able to easily read my code when I may need to debug it next month or next year.