3>2>1 returns logical 0?

32 visualizaciones (últimos 30 días)
Cian O'Regan
Cian O'Regan el 30 de Nov. de 2015
Editada: Stephen23 el 30 de Nov. de 2015
When I run 3>2>1 it returns logical 0 (false). Sorry if its a basic question but I can't understand how this is not true.

Respuesta aceptada

Stephen23
Stephen23 el 30 de Nov. de 2015
Editada: Stephen23 el 30 de Nov. de 2015
The basic problem is that you are attempting two logical relations simultaneously: MATLAB's relational operators are binary operators, so they only support one comparison at once. In summary:
X<A<Y % is NOT valid for comparing A against X and Y
X<A & A<Y % This compares A with both X and Y
In MATLAB logical relational operators follow the standard rules of operator precedence. Look at this example carefully:
>> 3<4<2
ans =
1
The output is true, so does this mean that 4<2 ? Of course not, we just have to remember the operator precedence rules, just like in high school. This is evaluated according to those rules as:
>> (3<4)<2
ans =
1
where
>> 3<4
ans =
1
So 3<4<2 is actually equivalent to 1<2, which is of course very true:
>> 1<2
ans =
1

Más respuestas (2)

Guillaume
Guillaume el 30 de Nov. de 2015
You cannot chain comparisons. You have to use logical operators.
3>2>1
is the same as
(3>2) > 1
which evaluates to
true > 1
which is false since true is the same as 1.
To do what you want:
3>2 && 2>1

William
William el 30 de Nov. de 2015
Editada: William el 30 de Nov. de 2015
I think the compiler probably solves this:
(3>2)>1
ans =
0
i.e 1>1= 0

Categorías

Más información sobre Functions en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by