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 个)
Guillaume
2018-1-11
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
2018-1-11
编辑:John D'Errico
2018-1-11
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.)
类别
在 帮助中心 和 File Exchange 中查找有关 Get Started with MATLAB 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!