Method on @sym: s = fortran (g)
Method on @sym: s = fortran (g1, …, gn)
Method on @sym: fortran (…, 'file', filename)
Method on @sym: [F, H] = fortran (…, 'file', '')

Convert symbolic expression into Fortran code.

Example returning a string of Fortran code:

syms x
g = taylor(log(1 + x), x, 0, 'order', 5);
g = horner(g)
  ⇒ g = (sym)
        ⎛  ⎛  ⎛1   x⎞   1⎞    ⎞
      x⋅⎜x⋅⎜x⋅⎜─ - ─⎟ - ─⎟ + 1⎟
        ⎝  ⎝  ⎝3   4⎠   2⎠    ⎠
fortran(g)
  ⇒ x*(x*(x*(1.0d0/3.0d0 - 1.0d0/4.0d0*x) - 1.0d0/2.0d0) + 1)

We can write to a file or obtain the contents directly:

[f90, h] = fortran(g, 'file', '', 'show_header', false);
f90.name
  ⇒ file.f90
h.name
  ⇒ file.h

disp(f90.code)
  -|  REAL*8 function myfun(x)
  -|  implicit none
  -|  REAL*8, intent(in) :: x
  -|
  -|  myfun = x*(x*(x*(1.0d0/3.0d0 - 1.0d0/4.0d0*x) - 1.0d0/2.0d0) + 1)
  -|
  -|  end function

disp(h.code)
  -|  interface
  -|  REAL*8 function myfun(x)
  -|  implicit none
  -|  REAL*8, intent(in) :: x
  -|  end function
  -|  end interface

FIXME: This doesn’t write “optimized” code like Matlab’s Symbolic Math Toolbox; it doesn’t do “Common Subexpression Elimination”. Presumably the compiler would do that for us anyway. Sympy has a “cse” module that will do it. See: http://stackoverflow.com/questions/22665990/optimize-code-generated-by-sympy

See also: @sym/ccode, @sym/latex, @sym/function_handle.

Package: symbolic