Not getting the right output for my if statement? [piecewise function]

(Ajay deleted this so I (MF) am restoring it).
% code
function y = FcnEval(x)
if x < -2
y= -1./ ((x.^2) + 1)
elseif -2 <= x < -1
y= sin(x)
elseif -1 <= x < 1
y= x.^2
elseif 1 <= x < 2
y=2
else x >= 2
y=1./(x+1)
end
but when I run the test case: x1 = 3; x2 = -2:2;
y1 = FcnEval(x1)
y2 = FcnEval(x2)
I'm supposed to get y1 = 0.2500
y2= -0.9093 1.0000 0 2.0000 0.3333
what am i doing wrong?

댓글 수: 3

Meaningful part of the question has been edited out of existence by the original poster :(
There is no such thing as an "if loop", just if statements.
Saved from google cache:
% code
function y = FcnEval(x)
if x < -2
y= -1./ ((x.^2) + 1)
elseif -2 <= x < -1
y= sin(x)
elseif -1 <= x < 1
y= x.^2
elseif 1 <= x < 2
y=2
else x >= 2
y=1./(x+1)
end
but when I run the test case: x1 = 3; x2 = -2:2;
y1 = FcnEval(x1)
y2 = FcnEval(x2)
I'm supposed to get y1 = 0.2500
y2= -0.9093 1.0000 0 2.0000 0.3333
what am i doing wrong?

댓글을 달려면 로그인하십시오.

 채택된 답변

Daniel Shub
Daniel Shub 2012년 10월 8일
편집: Daniel Shub 2012년 10월 8일

1 개 추천

First off, I doubt your code runs since else if is not valid syntax. Second, I am pretty sure that 1 <= x < 2 is not doing what you think it is doing.

댓글 수: 5

i fixed my syntax and it is running, but i'm not getting the correct answers (everything outputs to "2") I still don't get what is wrong with the function?
Again, 1 <= x < 2 is not doing what you think. Do you expect 1 <= 10 < 2 to be true (1) or false (0)? What does MATLAB say? Do you understand why?
Daniel is exactly right.
MATLAB evaluates
1 <= x < 2
as:
(1 <= x) < 2
So no matter whether x is greater than or less than 1, the result of evaluating the expression in parenthesis is always less than 2! Thus all of these are true:
tf = 1 <= -inf < 2
tf = 1 <= inf < 2
tf = 1 <= 0 < 2
thanks guys i just fixed it. I wasn't aware that the notation for a piecewise function was differently portrayed in matlab. I'm still not quite getting the right answer for the last part, but it's good to know I'm on the right track!
What do you think MATLAB should do with
if 1 <= -2:2 & -2:2 < 2
disp('true');
else
disp('false');
end
MATLAB does exactly what you tell it to do. You need to be careful with arrays ...

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2012년 10월 8일

Community Treasure Hunt

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

Start Hunting!

Translated by