Derivative Graph showing the orignal function and first derivative as the same on graph?

5 次查看(过去 30 天)
So heres my function so far, it calculates the first and second derivative and then plots all three. Everything is working fine, except the first derivative and the original function are showing up as the same line on my graph, and it keeps coming up as a flat line along the x axis.
The holds are only there because I originally had plot(x,y,x,yp,x,ypp) and wanted to see if it would help to put them in separate plots
Also the axes is showing up with weird values so I tried to have it auto adjust to x and y, but that does not affect anything, Im really not sure what to do as everywhere ive looked says to do what I have
function derivative_krr(f,x0)
h = .000001; x = linspace(-10,10);
y = f(x);
yp = (f(x-h)-f(x))/h;
ypp = (f(x-2*h)-2*f(x-h)-f(x))/h^2;
disp(f(x))
disp(yp)
disp (ypp)
plot(x,y); hold on; plot(x,yp); hold on; plot(x,ypp)
title('Graphing a Function, First and Second Derivative')
xlabel('X Axis')
ylabel('Y Axis')
legend('function', 'first derivative', 'second derivative')
axis auto xy

回答(1 个)

Star Strider
Star Strider 2015-5-8
I’m not sure where you got your second-order difference equation, but there must have been a typo in it. (It was producing values on the order of 1E+12, that was making your plots look strange.) I used the second-order forward difference equation (from the Wikipedia article on Finite difference) and everything works as it should.
Substitute this in the ‘ypp’ assignment:
ypp = (f(x+2*h)-2*f(x+h)+f(x))/h^2;
This test function makes an interesting plot:
f = @(x) exp(-0.1*x).*sin(x);
  2 个评论
Keith Rogers
Keith Rogers 2015-5-8
thank you so much! thats so infuriating it was just a algebraic error.. Now that that is fixed though, I have to ask, is there a way where I can get the command window to not fill up with the column values? I was trying to display a table of yp and ypp values at whatever input point you choose, which I think I had but now its not visible with all the values popping up
Star Strider
Star Strider 2015-5-8
My pleasure!
To keep the Command Window from filling up, delete (or comment-out) these three lines:
disp(f(x))
disp(yp)
disp (ypp)
I commented them out.
The plot is enough to show that your code works. If you want to return the values of the derivatives to display later, return them as outputs in your function. Then you can display them at your leisure in your main script.
For instance the first line of your function would then become:
function [yp, ypp] = derivative_krr(f,x0)
and then call it from your main script as:
[yp, ypp] = derivative_krr(f,x0);
to put the derivatives in your main script workspace.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 2-D and 3-D Plots 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by