Generating a Plot For a Function, HELP

When i go to run this code, it just keeps telling me to 'Enter a Value:' and will not show me any plot. I understand that this is my input, but i just want it to plot the values of x for (-10:10). Am i using the right commands?
function output=myfun(x)
x=input('Enter a Value:');
if x<-2
output=-x.^2;
elseif (-2<=x)&&(x<0)
output=-2.*x;
elseif (0<=x)&&(x<=2) output=2.*x;
elseif x>2
output=x.^2;
end
fplot(myfun(-10:10),output)
xlabel('x(m)')
ylabel('f(x)')

 Réponse acceptée

Geoff Hayes
Geoff Hayes le 3 Juil 2014
David - the code is getting stuck due to its recursive nature. The line
fplot(myfun(-10:10),output)
calls itself, passing the vector -10:10, only to reach this line again and again. So that is why the request for an input keeps popping up.
If you are just trying to plot the data from -10:10, then you can skip the request for an input and just define your function as follows
function [output] = myfun(x)
if x<-2
output=-x^2;
elseif (-2<=x)&&(x<0)
output=-2*x;
elseif (0<=x)&&(x<=2)
output=2*x;
elseif x>2
output=x^2;
end
Now to plot your above function for the interval [-10,10], just do something similar to what you had already, using fplot
fplot(@myfun,[-10,10])

Plus de réponses (0)

Catégories

En savoir plus sur Agriculture dans Centre d'aide et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by