Help on this piece-wise function?

6 次查看(过去 30 天)
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?

采纳的回答

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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Mathematics 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by