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

2 views (last 30 days)
(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 Comments
Matt Fig
Matt Fig on 9 Oct 2012
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?

Sign in to comment.

Accepted Answer

Daniel Shub
Daniel Shub on 8 Oct 2012
Edited: Daniel Shub on 8 Oct 2012
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 Comments
Ajay
Ajay on 8 Oct 2012
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!
Daniel Shub
Daniel Shub on 8 Oct 2012
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 ...

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!