double conditional in one line

5 次查看(过去 30 天)
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?

采纳的回答

Steven Lord
Steven Lord 2023-6-5
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
y = logical
0
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
y = logical
0
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 = logical
1
z = (0.1 < x) < 1.1
z = logical
1
z = true < 1.1
z = logical
1
x = Inf;
z = 0.1<x<1.1
z = logical
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)
z = logical
0

更多回答(2 个)

Matt J
Matt J 2023-6-5
编辑:Matt J 2023-6-5
You need to be using '&'
x=0.23;
0<x & x<1
ans = logical
1

Les Beckham
Les Beckham 2023-6-5
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
ans = logical
1
and this one 0<x<y<2 is written like this
x=1;
y=2;
0<x && x<y && y<2
ans = logical
0
  2 个评论
Antonio Baeza
Antonio Baeza 2023-6-5
Oh, yes, I know how to make a regular conditional. I was junt wondering how the double one works. Many thanks @Les Beckham and @Matt J

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Startup and Shutdown 的更多信息

产品


版本

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by