How can I plot a string function
2 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
回答(3 个)
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))
0 个评论
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
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".
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Two y-axis 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!