C code representation of symbolic expression
ccode(
uses additional options specified by one or more f
,Name,Value
)Name,Value
pair arguments.
Generate C code from the symbolic expression
log(1+x)
.
syms x f = log(1+x); ccode(f)
ans = ' t0 = log(x+1.0);'
Generate C code for the 3-by-3 Hilbert matrix.
H = sym(hilb(3)); ccode(H)
ans = ' H[0][0] = 1.0; H[0][1] = 1.0/2.0; H[0][2] = 1.0/3.0; H[1][0] = 1.0/2.0; H[1][1] = 1.0/3.0; H[1][2] = 1.0/4.0; H[2][0] = 1.0/3.0; H[2][1] = 1.0/4.0; H[2][2] = 1.0/5.0;'
Because generated C code initializes only non-zero elements,
you can efficiently initialize arrays by setting all elements to
0
directly in your C code. Then, use the generated C code
to initialize only nonzero elements. This approach enables efficient
initialization of matrices, especially sparse matrices.
Initialize the 3-by-3 identity matrix. First initialize the matrix with
all elements set to 0
in your C code. Then use the
generated C code to initialize the nonzero values.
I3 = sym(eye(3)); I3code = ccode(I3)
I3code = ' I3[0][0] = 1.0; I3[1][1] = 1.0; I3[2][2] = 1.0;'
Write C code to the file ccodetest.c
by
specifying the File
option. When writing to a file,
ccode
optimizes the code by using intermediate
variables named t0
, t1
, and so on.
syms x f = diff(tan(x)); ccode(f,'File','ccodetest.c')
t0 = pow(tan(x),2.0)+1.0;
Include the comment Version: 1.1
in the file by using
the Comments
option. ccode
uses
block comments.
ccode(f,'File','ccodetest.c','Comments','Version: 1.1')
/* Version: 1.1 */ t0 = pow(tan(x),2.0)+1.0;
f
— Symbolic inputSymbolic input, specified as a symbolic expression.
Specify optional
comma-separated pairs of Name,Value
arguments. Name
is
the argument name and Value
is the corresponding value.
Name
must appear inside quotes. You can specify several name and value
pair arguments in any order as
Name1,Value1,...,NameN,ValueN
.
ccode(x^2,'File','ccode.c','Comments','V1.2')
'File'
— File to write toFile to write to, specified as a character vector or string. When
writing to a file, ccode
optimizes the code by
using intermediate variables named t0
,
t1
, and so on.
'Comments'
— Comments to include in file headerComments to include in the file header, specified as a character
vector, cell array of character vectors, or string vector. Because
ccode
uses block comments, the comments must
not contain /*
or */
.