Help on this piece-wise function?

6 views (last 30 days)
NikePro
NikePro on 25 Feb 2016
Answered: Star Strider on 25 Feb 2016
I am trying to make a function called f that satisfied the following criteria: For values of x>2, f(x) = x2 For values of x<=2, f(x) = 2x I then need to plot my results from -3 to 5.
Here is what i have so far;
function y = f(x)
% first piece
x1 = x(x > 2);
y(find(x > 2)) = x1 .^ 2;
% second piece
x2 = x(x <= 2);
y(find(x <= 2)) = 2 * x2;
x = -3 : 0.5 : 5;
y = f(x);
plot(x, y)
However i keep getting an error in line three stating... Error in f (line 3) x1 = x(x > 2);
Could i get some help on this?

Accepted Answer

Star Strider
Star Strider on 25 Feb 2016
This works:
f = @(x) [(x<=2).*(x*2) + (x>2).*(x.^2)];
x = linspace(-3, 5);
figure(1)
plot(x, f(x))
grid

More Answers (0)

Categories

Find more on Mathematics 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!