Generate C formatted string
MuPAD® notebooks are not recommended. Use MATLAB® live scripts instead.
MATLAB live scripts support most MuPAD functionality, though there are some differences. For more information, see Convert MuPAD Notebooks to MATLAB Live Scripts.
generate::C(e) generates C code for the MuPAD® expression
generate::C returns a C formatted string
representing an expression, equation, list of equations or a matrix.
An equation represents an assignment in C code. The type of
the assignment is
When generating C code for a matrix, the generator assigns only nonzero elements. See Example 3.
To print an output string to a file, use the
fprint function. Use
the printing option
Unquoted to remove quotation
marks and to expand special characters like line breaks and tabs.
NoWarning option lets you suppress warnings.
See Example 6.
The code generator converts a list of equations to a sequence of assignments:
generate::C([x1 = y2^2*(y1 + sin(z)), x2 = tan(x1^4)]): print(Unquoted, %)
x1 = (y2*y2)*(y1+sin(z)); x2 = tan(x1*x1*x1*x1);
MuPAD matrix and array indexing differs from C array indexing.
By default, MuPAD array indices start with 1, and C array indices
start with 0. To create the code compatible with the default indexing
in C, the
generate::C function decrements each
index by one:
A:= matrix([[1,2],[3,4]]): generate::C(A)."\n". generate::C(hold(Determinante = A[1,1]*A[2,2] - A[1,2]*A[2,1])): print(Unquoted, %)
A = 1.0; A = 2.0; A = 3.0; A = 4.0; Determinante = A*A-A*A;
Generated C code does not include assignments for zero elements of a matrix:
A:= matrix([[1, 0, 0],[0, 0, 1]]): print(Unquoted, generate::C(A))
A = 1.0; A = 1.0;
If the first index of an array is not 1, the
issues a warning:
A:= array(1..2, 2..3, [[1,2],[3,4]]): print(Unquoted, generate::C(A))
Warning: Array index 'A[1..2, 2..3]' out of range 1..n.
A = 1.0; A = 2.0; A = 3.0; A = 4.0;
generate::C function does not optimize
print(Unquoted, generate::C([x = a + b, y = (a + b)^2])):
x = a+b; y = pow(a+b,2.0);
You can use the
generate::optimize function before converting
your MuPAD expression to C code. For example, this function can reduce
the number of operations by finding common subexpressions:
print(Unquoted, generate::C( generate::optimize([x = a + b, y = (a + b)^2]) )):
x = a+b; y = x*x;
By default, the
generate::C function can
Warning: Function 'f' not verified to be a valid C function.
t0 = f(x);
If you started using
the warnings can help you identify the potential issues in the converted
code. If you want to suppress warnings, use the
print(Unquoted, generate::C(f(x), NoWarning))
t0 = f(x);
An expression, equation, list of equations, or a matrix
generate::C returns a string containing