Thursday, February 4, 2016

A simple finite differencing example using Matlab/Octave

Listening to the queries of some students and researchers, a need was felt for writing a small and simple tutorial blog post giving a simple finite differencing example using Matlab/Octave.

Taking 'x' as the independent variable and 'f(x) = sin(x)' as the dependent variable, the attached code demonstrates the calculation of first two derivatives.

In the code, taking xVec (= x0, x2, x3 .... xn) to represent the nodal values of 'x',

y1 = sin(xVec);


y3 = cos(xVec);

the derivatives of f(x) at the nodal points are calculated as:

1st derivative:y2 = Dmatx*y1;% dy/dx = Dmatx * y1

2nd derivative:
y4 = Dmatx*Dmatx*y1;% d2y/dx2 = Dmatx * Dmatx * y1

It must be obvious that (y1, y2, y3, y4) are ((n + 11) by 1) vectors and Dmatx is (n + 1) dimension square matrix.

The resulting plots:

For 1at derivative (with n = 10):

For 2nd derivative (with n = 10):

For 1st derivative (with n = 20):
For 2nd derivative (with n = 20):

Please do contact/comment for your suggestions, clarifications etc.


Happy Matlabbing/Octaving!

No comments:

Post a Comment