MATLAB: Help on this piece-wise function

MATLABpiecewise

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?

Best Answer

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