Help with specific fplot
显示 更早的评论
I have no problem using fplot with any other function I have created except for one. I am trying to graph f(x)=x^2-sin(x)+1/x over -pi<x<pi and cannot get the proper graph to save my life. Here is my code:
EDU>> f=@(x)x.^2-sin(x)+1./x;
EDU>> fplot(f,[-pi,pi]);
The resulting incorrect graph is a horizontal line y=0 with a spike towards y=inf as you approach x=0.
Any help would be appreciated, pulling my hair out over this one haha.
回答(1 个)
Star Strider
2015-8-13
1 个投票
The plot is correct. You’re plotting it from [-pi,pi]. That includes zero, and the 1/x term approaches +Inf as x approaches zero.
5 个评论
Andrew
2015-8-13
Star Strider
2015-8-13
That is an artefact of the way fplot divides the interval. You can get the x-data from fplot:
xd = fplot(f, [-pi,pi]);
that shows (as part of an 89-element vector):
-50.2655e-003
-37.6991e-003
-25.1327e-003
-12.5664e-003
2.1406e-015
12.5664e-003
25.1327e-003
50.2655e-003
so it’s evaluating the 1/x term here at 2.1406e-015, producing only a positive deflection as the values approach zero. Using linspace to define x with the default 100 values, then using plot to plot it produces the expected result. So fplot is not actually wrong, but simply imprecise.
Walter Roberson
2015-8-13
The plot is correct to the scaling. Look at
fplot(f,[-pi,-10/1000])
and you will see that the drop to -inf is quite narrow; as you try with -9/1000 and -8/1000 and so on you can see that with that small change in range the plot gets much sharper. If fplot does not happen to try a value in the range about between -1/100 and 0 then it is not going to have much of downstroke to counter the massive upstroke at exactly 0.
Compare:
fplot(f,[-pi-1/100,pi-1/100])
which slightly changes the sampling positions, reducing the huge spike.
Andrew
2015-8-13
Star Strider
2015-8-13
Our pleasure!
类别
在 帮助中心 和 File Exchange 中查找有关 Line Plots 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!