Is this a MATLAB bug? (Logical expression)
조회 수: 1 (최근 30일)
이전 댓글 표시
Hello,
I have just found something that I really don't understand...
Say I have a variable called x1 which has a value of 1, and a variable x2 which has a value of 2.
Now, if I logically say "x1 or x2 is greater than 1", I should get 1, as x2 is indeed greater than 1.
And if I type this:
x1 = 1;
x2 = 2;
x1|x2>1
I get a logical "1" as answer, as expected.
However it would seem to me that writing this would yield exactly the same result, as I just add some parenthesis:
x1 = 1;
x2 = 2;
(x1|x2)>1
But instead I get a logical "0" here. What am I missing? Why are the answers different from each other?
Thank you!
댓글 수: 0
채택된 답변
Jan
2022년 3월 25일
편집: Jan
2022년 3월 25일
(x1 | x2) is TRUE, if at least one of them is not zero. If both are zero, FALSE is replied. In the next step TRUE is converted to 1 and FALSE to 0. Neither 1 nor 0 is greater than 1, so the expression (x1 | x2) > 1 replies FALSE as expected.
Your expression "x1 or x2 is greater than 1" means something else:
(x1 > 1) | (x2 > 1)
You can combine this in English, but not in Matlab or other similar programming languages.
The different between "x1 | x2 > 1" and "(x1 | x2) > 1" is the precedence order. In the first one, the > operator has a higher precedence than the | , so X2 > 1 is evaluated at first. Then you get x1 | FALSE, which is TRUE, because x1 is not zero.
댓글 수: 1
Steven Lord
2022년 3월 25일
To put it another way, the expressions x1 | x2 > 1 and (x1 | x2) > 1 are not equivalent. The expressions x1 | x2 > 1 and x1 | (x2 > 1) are equivalent. Jan correctly wrote out the expression equivalent to the intent of your English description, (x1 > 1) | (x2 > 1).
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!