To use central difference approximation to compute the first derivative of a function with increasingly smaller values of h
in MATLAB, we can define the following function:
main.m295 chars11 lines
We can then define the function we want to differentiate, e.g. f = @(x) sin(x)
, and loop over a range of decreasing values of h
while calling the centraldiff
function. Here's an example:
main.m252 chars10 lines
This will output:
main.m430 chars11 lines
As we can see, as h
gets smaller, the approximated derivative converges to the true value, which is 1 for f(x) = sin(x)
evaluated at x=1
.
gistlibby LogSnag