Help with specific fplot
Mostrar comentarios más antiguos
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.
Respuestas (1)
Star Strider
el 13 de Ag. de 2015
1 voto
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 comentarios
Andrew
el 13 de Ag. de 2015
Star Strider
el 13 de Ag. de 2015
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
el 13 de Ag. de 2015
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
el 13 de Ag. de 2015
Star Strider
el 13 de Ag. de 2015
Our pleasure!
Categorías
Más información sobre Line Plots en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!