필터 지우기
필터 지우기

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

조회 수: 1 (최근 30일)
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
John D'Errico 2022년 10월 9일
편집: John D'Errico 2022년 10월 9일
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
Steven Lord
Steven Lord 2022년 10월 10일
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.

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

VBBV
VBBV 2022년 10월 9일
편집: VBBV 2022년 10월 9일
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 2022년 10월 9일
8/2<(5*3+1) & (5*3+1)>9
ans = logical
1

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by