Partial derivative

MATLAB has two diff routines:

  1. diff(X) to calculate differences and approximate derivatives
  2. diff(f,var) to differentiate a symbolic expression or function.

I guess the second one is what you had in mind. Here’s a MATLAB script, which generates the Jacobian for the shape functions given by @Ashok:

syms s t real

N1 = (1-s)*(1-t)/4;
N2 = (1-s)*(1+t)/4;
N3 = (1+s)*(1+t)/4;
N4 = (1+s)*(1-t)/4;

J = jacobian([N1,N2,N3,N4],[s, t]);

fortran(J,'file','four_node_jac.inc');

The resulting Fortran code:

      t2 = s/4.0D0
      t3 = t/4.0D0
      t4 = -t2
      t5 = -t3
      A0(1,1) = t3-1.0D0/4.0D0
      A0(1,2) = t2-1.0D0/4.0D0
      A0(2,1) = t5-1.0D0/4.0D0
      A0(2,2) = t4+1.0D0/4.0D0
      A0(3,1) = t3+1.0D0/4.0D0
      A0(3,2) = t2+1.0D0/4.0D0
      A0(4,1) = t5+1.0D0/4.0D0
      A0(4,2) = t4-1.0D0/4.0D0

You’d probably want to edit this to match expected variables names, or change the precision.

SymPy has a more customizable Fortran code printer compared to MATLAB; see Fortran printing in the SymPy documentation. A previous post of mine gives a complete example: Code generation using SymPy.

3 Likes