double conditional in one line
19 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Antonio Baeza
am 5 Jun. 2023
Kommentiert: Les Beckham
am 5 Jun. 2023
By chance I tried a sentence like
0<x<1
i cannot find any documentation for this.
At the beginnnig looks like weird
>> x=0.23: 0<x<1
ans =
logical
0
but
>> x=0.23: 0.1<x<1.1
ans =
logical
1
You can concatenate more, exemple
>> x=1; y=2; 0<x<y<2
ans =
logical
1
I still cannot figure out how it really works. Any help?
0 Kommentare
Akzeptierte Antwort
Steven Lord
am 5 Jun. 2023
At the beginnnig looks like weird
>> x=0.23: 0<x<1
This does not ask the question "Is x between 0 and 1 exclusive?" It is instead interpreted as:
x = 0.23;
y = (0 < x) < 1
The first part of the expression for y, (0 < x), returns either false (treated as 0) or true (treated as 1) depending on the value you specified for x. In this case since 0 is less than 0.23, it is true. So y becomes:
y = true < 1
Since true is treated as 1 and 1 is not less than 1, y is false.
Your second expression, x=0.23: 0.1<x<1.1, will always return true. Both false (0) and true (1) are strictly less than 1.1 so it doesn't matter whether 0.1 is less than x or not.
x = 0.23;
z = 0.1<x<1.1
z = (0.1 < x) < 1.1
z = true < 1.1
x = Inf;
z = 0.1<x<1.1
If you enter this in the Editor, Code Analyzer should warn about that pattern and suggest the approach others have already recommended earlier, using two separate tests combined using the & or && operators.
x = 2;
z = (0.1 < x) & (x < 1.1)
Weitere Antworten (2)
Les Beckham
am 5 Jun. 2023
You have to join the multiple conditions with a logical operator. For example, the condition 0<x<1 is written like this
x=0.23;
0<x && x<1
and this one 0<x<y<2 is written like this
x=1;
y=2;
0<x && x<y && y<2
2 Kommentare
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements 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!