Generate C or Fortran Code

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;
ans =
      t0 = (x**4*3.0D1)/(x*y**2+1.0D1)-x**3*(y**2+1.0D0)**2
ans =
  t0 = ((x*x*x*x)*3.0E1)/(x*(y*y)+1.0E1)-(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:

      t12 = x**2
      t13 = y**2
      t14 = t13+1
      t0 = (t12**2*30)/(t13*x+10)-t12*t14**2*x

Similarly, the command


generates a file named ccodetest that consists of the lines

  t16 = x*x;
  t17 = y*y;
  t18 = t17+1.0;
  t0 = ((t16*t16)*3.0E1)/(t17*x+1.0E1)-t16*(t18*t18)*x;

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, for example t32. Intermediate variables can make the resulting code more efficient by reusing intermediate expressions (such as t12 in fortrantest, and t16 in ccodetest). They can also make the code easier to read by keeping expressions short.

If you work in the MuPAD® Notebook app, see generate::C and generate::fortran.

Was this topic helpful?