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!