Matlab - Trying to calculate the Numeric Derivation

317 Views Asked by At

So the assignment states as following:

Type an m-file numerical_derivative.m that performs numerical derivation. Use it to calculate $f'(-3)$ when $f(x) = 3x^2 /(\ln(1-x))$.

In the m-file, you have to use $h = 10^{-6}$. The file should have the following main function:

function y = numericalderivative (f, x)
% Calculates the numerical value in the case of f in punk x.
% --- Input ---
% f: function handle f(x)
% x: the point where the derivative is calculated
% --- output ---
% y: the numerical derivative of f on the point x

If I want to save it as a file and run the program in Matlab, doesn't it make it redundant to use a function?

function y= numerical_derivative(dxdy,x)
h=10.^-6;
func = @(x) (3*x^2)/log(1-x);
x = -3;
numerical_derivative = @(x)((x+h)-(x))./h;
dxdy = numerical_derivative(func,x);
end

This is what I've got, but it won't run. Any help would be greatly appreciated!

1

There are 1 best solutions below

0
On

You have hindered yourself by re-labeling f to the non-sensical dxdy in the call format. What you should have done is to strictly implement divided differences

dydx = ( f(x+h) - f(x-h) ) / ( 2*h )

Thus the implementation of numericalderivative has one line.


Bytheway, the h=1e-6 is in the optimal range for the one-sided difference quotient, for the symmetric the optimal range is h=1e-4 toh=1e-3, as one can confirm with error plots using the graphical tool of your choice, here gnuplot

# implement f(x)=(3*x^2)/log(1-x) in steps with derivatives
u(x) = 3*x**2;   du(x) = 6*x;
v(x) = log(1-x); dv(x) = -1./(1-x);
f(x) = u(x)/v(x); df(x) = du(x)/v(x)-u(x)*dv(x)/v(x)**2

set logscale xy
set format xy "%.1e"
set samples 3001
a=-3; dfa = df(a);
set multiplot layout 2,1
plot [1e-12:1e-2] abs((f(a+x)-f(a))/(x)-dfa) with dots lw 2 title 'one-sided'
plot [1e-12:1e-2] abs((f(a+x)-f(a-x))/(2*x)-dfa) with dots lw 2 title 'symmetric'
unset multiplot

enter image description here