Is this a MATLAB bug? (Logical expression)

12 Ansichten (letzte 30 Tage)
Andrea Angella
Andrea Angella am 25 Mär. 2022
Kommentiert: Steven Lord am 25 Mär. 2022
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!

Akzeptierte Antwort

Jan
Jan am 25 Mär. 2022
Bearbeitet: Jan am 25 Mär. 2022
(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 Kommentar
Steven Lord
Steven Lord am 25 Mär. 2022
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).

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Produkte


Version

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by