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
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
Andrew 2015 年 8 月 13 日
The plot is not correct though. When I plot using plot(x,y) it is the correct graph. If you look at the function, f(x) should be going to inf from the right of 0 and -inf from the left, which is not what I am getting with fplot, hence the hairpulling haha. How do you post graphs on this forum? I will post the correct and incorrect graph.
Star Strider
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
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
Andrew 2015 年 8 月 13 日
Awesome. Thanks guys.
Star Strider
Star Strider 2015 年 8 月 13 日
Our pleasure!

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeLine Plots についてさらに検索

タグ

質問済み:

2015 年 8 月 13 日

コメント済み:

2015 年 8 月 13 日

Community Treasure Hunt

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

Start Hunting!

Translated by