Order of logical operators
4 views (last 30 days)
Show older comments
Akash Sinhal
on 13 Oct 2018
Commented: John D'Errico
on 13 Oct 2018
1 < 5 > 2 gives false
1 Comment
John D'Errico
on 13 Oct 2018
There is no need to close a question that has had answers provided. In fact, doing so removes the value of the answer provided for others to read.
Accepted Answer
John D'Errico
on 13 Oct 2018
Edited: John D'Errico
on 13 Oct 2018
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.
More Answers (1)
KALYAN ACHARJYA
on 13 Oct 2018
Edited: KALYAN ACHARJYA
on 13 Oct 2018
Here Logic is false
1 < 5 > 2
1<5 gives 0
and 0>2 false
so Ans 0
If you do others
3>2>0 gives you 1
as 3>2 true gives 1, which is > 0
Ans 1
Hope it clears your doubt
2 Comments
KALYAN ACHARJYA
on 13 Oct 2018
Edited: KALYAN ACHARJYA
on 13 Oct 2018
Because 1<5 True its gives you 1, next 1>2 False, so result false
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!