if does not work
Show older comments
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 Comments
Answers (2)
Guillaume
on 11 Jan 2018
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
on 11 Jan 2018
Edited: John D'Errico
on 11 Jan 2018
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.)
Categories
Find more on Get Started with MATLAB in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!