# I do not understand why this script {8/2<5*3+1>9} with logical operators gives NO (0)?

2 views (last 30 days)
M Yasir Muneeb on 9 Oct 2022
Commented: Steven Lord on 10 Oct 2022 I do not understand why the answer is zero while the statement is apprarently correct. See below:
4<16>9
Isn't it correct? The answer should have been 1

John D'Errico on 9 Oct 2022
Edited: John D'Errico on 9 Oct 2022
Just because people use a specific mathematical shorthand, does not mean that shorthand is implemented in MATLAB syntax. In this case, we see the general shorthand
A < B > C
8/2 < 5*3+1 > 9
How does MATLAB see that? First, it evaluates the expression A = 8/2 = 4.
Remember that MATLAB knows what operators have the LOWEST priority among operators. They are the relational operators. So MATLAB does things like add, subtract, multiply and divide FIRST. That means MATLAB next computes the sub-expression 5*3-1 = 16. It stops there, since the next operator it sees is another relational operator. So it then performs the previous test, thus comparing 4 to 16. That returns a true value, so 1.
Finally MATLAB compares 1 to the number 9. Is 1 greater than 9? Of course not.
The point is, MATLAB sees the general expression above as:
(A < B) > C
where a relational test returns the number 1 or 0.
When in fact when YOU write that expression using the common mathematical shorthand we see, you are thinking of a different one, thus
(A < B) & (B > C)
The two results are completely different of course.
Is the above any different than the old student conundrum of how to compute something like this:
6/3 + 2
ans = 4
Some might think it is asking to compute 6/(3+2)=6/5, but that is clearly incorrect. MATLAB correctly evaluates the expression as
(6/3) + 2
yielding 4, since a divide has a higher operator priority than addition.
##### 2 CommentsShowHide 1 older comment
Steven Lord on 10 Oct 2022
Just FYI, for at least a couple years now Code Analyzer will warn on the first of the relational operators in that statement and suggest breaking that expression into two pieces.

VBBV on 9 Oct 2022
Edited: VBBV on 9 Oct 2022
Matlab evaluates the expression from left to right, If you start with numbers from left to right in your expression, it will first evaluate 8/2 which is 4. Then it compares the numbers on either side of inequality operator, which is again true,since 4 is less than (5*3+1) = 16.
After completing this step it returns a logical true or 1. Then it advances to compare the numbers on either side of > operator, is 1 > 9 ? No. So, it returns a logical 0 at the end.
M Yasir Muneeb on 10 Oct 2022
Thankyou brother, I got the answer 🙏.

KSSV on 9 Oct 2022
8/2<(5*3+1) & (5*3+1)>9
ans = logical
1
M Yasir Muneeb on 10 Oct 2022
Thanks