Main Content

Generate C or Fortran Code from Symbolic Expressions

You can generate C or Fortran code fragments from a symbolic expression, or generate files containing code fragments, using the ccode and fortran functions. These code fragments calculate numerical values as if substituting numbers for variables in the symbolic expression.

To generate code from a symbolic expression g, enter either ccode(g) or fortran(g).

For example:

syms x y
z = 30*x^4/(x*y^2 + 10) - x^3*(y^2 + 1)^2;
fortran(z)
ans =
    '      t0 = (x**4*3.0D+1)/(x*y**2+1.0D+1)-x**3*(y**2+1.0D0)**2'
ccode(z)
ans =
    '  t0 = ((x*x*x*x)*3.0E+1)/(x*(y*y)+1.0E+1)-(x*x*x)*pow(y*y+1.0,2.0);'

To generate a file containing code, either enter ccode(g,'file','filename') or fortran(g,'file','filename'). For the example above,

fortran(z, 'file', 'fortrantest')

generates a file named fortrantest in the current folder. fortrantest consists of the following:

      t2 = y**2
      t0 = (x**4*3.0D+1)/(t2*x+1.0D+1)-x**3*(t2+1.0D0)**2

Similarly, the command

ccode(z,'file','ccodetest')

generates a file named ccodetest that consists of the lines

  t2 = y*y;
  t0 = ((x*x*x*x)*3.0E+1)/(t2*x+1.0E+1)-(x*x*x)*pow(t2+1.0,2.0);

ccode and fortran generate many intermediate variables. This is called optimized code. MATLAB® generates intermediate variables as a lowercase letter t followed by an automatically generated number, such as t2. Intermediate variables can make the resulting code more efficient by reusing intermediate expressions (such as t2 in fortrantest and ccodetest). They can also make the code easier to read by keeping expressions short.