You are on page 1of 1

A simple example listed below is given here:

% Finite difference example: cubic function


% f(x)=x^3+x^2-1.25x-0.75
% finite difference approximation to 1st derivative, error O(h)
x=-2:0.1:1.2;
plot(x, polyval([3 2 -1.25],x), 'g-'); % analytical 1st derivative
h=0.4; % step size
n=(1.2-(-2))/h+1;
x=-2:h:1.2
f=polyval([1, 1, -1.25, -0.75], x)
f1=conv([1, -1], f) % finite differences, only f1(2:9) are useful
f1=f1(2:9)/h % approximation to 1st derivative
hold on; % keep the above graph
plot(x(1:8)+h/2, f1,'r-'); % FD approximation to 1st derivative
hold off;
It approximates the 1st derivative of the polynomial function f(x) = x 3 + x2 - 1.25x 0.75 using the forward difference method. Both, the approximated and the
analytical derivatives of the f(x) functions are depicted for comparison purposes.
The green curve represents the analytical derivative of the f(x) function, while te
red curve is its approximation.

You might also like