How can I plot a string function

2 views (last 30 days)
Eman Ahmed Elsayed
Eman Ahmed Elsayed on 4 Jun 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

Answers (3)

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

Matt Fig
Matt Fig on 4 Jun 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 on 4 Jun 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 Comments
Walter Roberson
Walter Roberson on 4 Jun 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 on 5 Jun 2011
My apologies, I will fix my answer.

Sign in to comment.

Categories

Find more on Two y-axis in Help Center and File Exchange

Tags

Products

Community Treasure Hunt

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

Start Hunting!