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

1 Ansicht (letzte 30 Tage)
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

Akzeptierte Antwort

John D'Errico
John D'Errico am 9 Okt. 2022
Bearbeitet: John D'Errico am 9 Okt. 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
In your case, you wrote
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.
You will want to read this page:
  2 Kommentare
Steven Lord
Steven Lord am 10 Okt. 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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (2)

VBBV
VBBV am 9 Okt. 2022
Bearbeitet: VBBV am 9 Okt. 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.

KSSV
KSSV am 9 Okt. 2022
8/2<(5*3+1) & (5*3+1)>9
ans = logical
1

Kategorien

Mehr zu Programming finden Sie in Help Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by