double conditional in one line

조회 수: 6 (최근 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 CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품


릴리스

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by