How can I plot a string function

조회 수: 2 (최근 30일)
Eman Ahmed Elsayed
Eman Ahmed Elsayed 2011년 6월 4일
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

답변 (3개)

Andrei Bobrov
Andrei Bobrov 2011년 6월 4일
ezplot('x^2+3*x+2+sin(x)')

Matt Fig
Matt Fig 2011년 6월 4일
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 2011년 6월 4일
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
Walter Roberson
Walter Roberson 2011년 6월 4일
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 2011년 6월 5일
My apologies, I will fix my answer.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Two y-axis에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by