Help on this piece-wise function?

6 vues (au cours des 30 derniers jours)
NikePro
NikePro le 25 Fév 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?

Réponse acceptée

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

Plus de réponses (0)

Catégories

En savoir plus sur Mathematics dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by