In: Computer Science
Using Matlab, consider the function f(x) = x^3 – 2x + 4 on the interval [-2, 2] with h = 0.25. Write the MATLAB function file to find the first derivatives in the entire interval by all three methods i.e., forward, backward, and centered finite difference approximations.
Could you please add the copiable Matlab code and the associated screenshots? Thank you!
Answer :-
%% Function f and its derivatives
f = @(x) x.^3-2*x+4;
f_1 = @(x) 3*x.^2 -2; % first derivative
f_2 = @(x) 6*x; % second derivative
h = 0.25;
%% First derivative finite difference approximations
f_1b = @(x) (f(x)-f(x-h))/h; % backward
f_1f = @(x) (f(x+h)-f(x))/h; % forward
f_1c = @(x) (f(x+h)-f(x-h))/(2*h); % centered
%% Second derivative finite difference approximations
f_2b = @(x) (f(x)-2*f(x-h)+f(x-2*h))/(h^2); % backward
f_2f = @(x) (f(x+2*h)-2*f(x+h)+f(x))/(h^2); % forward
f_2c = @(x) (f(x+h)-2*f(x)+f(x-h))/(h^2); % centered
%% Plotting
x = -2:0.1:2;
subplot(1,3,1)
plot(x, f(x))
legend('f(x)')
title('Function f')
subplot(1,3,2)
plot(x, f_1(x), 'r-*', x, f_1b(x), 'b', x, f_1f(x), 'm', x, f_1c(x) , 'g')
legend('df/dx', 'backward finite difference approximation of df/dx', 'forward finite difference approximation of df/dx', 'centered finite difference approximation of df/dx' )
title('First derivative of f and its approximations')
subplot(1,3,3)
plot(x, f_2(x), 'r-*', x, f_2b(x), 'b', x, f_2f(x), 'm', x, f_2c(x) , 'g')
legend('d^2f/dx^2', 'backward finite difference approximation of d^2f/dx^2', 'forward finite difference approximation of d^2f/dx^2', 'centered finite difference approximation of d^2f/dx^2' )
title('Second derivative of f and its approximations')
If you have any question feel free to ask...
Hope this may help you.
Thank you ??