double conditional in one line

14 ビュー (過去 30 日間)
Antonio Baeza
Antonio Baeza 2023 年 6 月 5 日
コメント済み: Les Beckham 2023 年 6 月 5 日
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
  1 件のコメント
Antonio Baeza
Antonio Baeza 2023 年 6 月 5 日
Thank you!. it is clear now

サインインしてコメントする。

その他の回答 (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
Les Beckham
Les Beckham 2023 年 6 月 5 日
You are quite welcome.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品


リリース

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by