I do not understand why this script {8/2<5*3+1>9} with logical operators gives NO (0)?
1 回表示 (過去 30 日間)
古いコメントを表示
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1150075/image.png)
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
0 件のコメント
採用された回答
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
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
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
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.
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!