if does not work

k=1;
for ii=-100:0.01:100
ee(k)=ii/ey;
if ee(k)<-1
f(k)=-1;
elseif -1<= ee(k)<= 1
f(k)=ee(k);
elseif ee(k)>1
f(k)=1;
end
k=k+1;
end
this statement does not work when ee(k)>1 any thoughts?

2 comentarios

M
M el 11 de En. de 2018
Editada: M el 11 de En. de 2018
Could you define does not work more precisely ?
How is ey defined ?
Guillaume
Guillaume el 11 de En. de 2018
Dim Mert comment mistakenly posted as an answer copied here:
ey=1.750
it doesn't go to the statement elseif ee(k)>1

Iniciar sesión para comentar.

Respuestas (2)

Guillaume
Guillaume el 11 de En. de 2018

1 voto

if works perfectly well. Your knowledge of matlab syntax is the problem.
You'll never find any reference documentation for matlab which uses
a <= b <= c
to test that b is between a and c. What the above test does is first execute a <= b. The result of that is either 0 (a is greater than c) or 1. It then compare that 0 or 1 to c. So your test is either
0 <= 1
or
1 <= 1
which is always true.
The proper to write the comparison is
a <= b && b <= c
so
elseif -1<= ee(k) && ee(k) <= 1
Or you could avoid the loop, and if test and use matlab the proper way with just
ii = -100:0.01:100
ee = ii/ey;
f = max(min(ee, 1), -1);
John D'Errico
John D'Errico el 11 de En. de 2018
Editada: John D'Errico el 11 de En. de 2018

1 voto

If DOES work. At least it does if you write the test properly.
elseif -1<= ee(k)<= 1
is wrong.
People never seem to recognize that while this is common shorthand for TWO distinct inequality statements, combined with an AND, that it does not do what they think in MATLAB.
While it does not cause a syntax error, it is NOT the test you think it is. MATLAB looks at that expression very literally. Start with:
-1<= ee(k)
It sees the above test. I.e., is -1 <= ee(k). The result is either true (1) or it is false (0). There are no other options. Then it takes that result, and compares if to the number 1. That after all, is exactly what you told it to do! In either case, 0<=1 and 1<=1. So the combined test as you have written it
elseif -1<= ee(k)<= 1
is ALWAYS true!
Instead, write that line as
elseif (-1 <= ee(k)) && (ee(k) <= 1)
(An extra set of parens applied for purposes of clarity.)

Categorías

Más información sobre Get Started with MATLAB en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 11 de En. de 2018

Editada:

el 11 de En. de 2018

Community Treasure Hunt

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

Start Hunting!

Translated by