Borrar filtros
Borrar filtros

How can I plot a string function

1 visualización (últimos 30 días)
Eman Ahmed Elsayed
Eman Ahmed Elsayed el 4 de Jun. de 2011
I want to plot a string function where y=x^2+3x+2+sin(x)
or any function.
I tried plot(y,x) but it doesn't work. and what's the right value of x which will be propariate to all functions

Respuestas (3)

Andrei Bobrov
Andrei Bobrov el 4 de Jun. de 2011
ezplot('x^2+3*x+2+sin(x)')

Matt Fig
Matt Fig el 4 de Jun. de 2011
Is there a particular reason why you are using a string instead of an anonymous function?
y = inline('x.^2+3*x+2+sin(x)'); % Inline function made from string
x = -5:.1:5;
plot(x,y(x))
Notice, that this is an older style of function, the newer and preferred style is to use anonymous functions:
y = @(x) x.^2+3*x+2+sin(x); % Anonymous function handle.
x = -5:.1:5;
plot(x,y(x))

Ian Wood
Ian Wood el 4 de Jun. de 2011
You can choose whatever values of x you want. Since you are dealing with a trigonometric function in your case, you may want to deal with radian values. Like this (very similar to what Matt Fig suggested):
y = @(x) x.^2+3*x+2+sin(x);
x = -2*pi:pi/16:2*pi;
plot(x,y(x))
If you prefer not to deal with anonymous functions, you could try this:
x = -2*pi:pi/16:2*pi;
y = x.^2+3*x+2+sin(x);
plot(x,y)
Note that if you choose the second option, x always has to come before y in declaration, otherwise you will get an error saying that x is undefined.
These two blocks of code execute the exact same way, but using anonymous functions is helpful, in that you don't have to repeat the statement of y, and simply just change the bounds on x.
  2 comentarios
Walter Roberson
Walter Roberson el 4 de Jun. de 2011
Ian, it is completely valid to submit points to plot() in any order one likes. plot() does *not* expect the second array of values to be one-to-one from the first array of values. plot() just treats what it is given as point components without expectation as to their "meaning".
Ian Wood
Ian Wood el 5 de Jun. de 2011
My apologies, I will fix my answer.

Iniciar sesión para comentar.

Categorías

Más información sobre Two y-axis en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by