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

7 views (last 30 days)
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

Answers (1)

Star Strider
Star Strider on 8 May 2015
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 Comments
Keith Rogers
Keith Rogers on 8 May 2015
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 on 8 May 2015
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.

Sign in to comment.

Categories

Find more on 2-D and 3-D Plots in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!