@sym: s = ccode (f) ¶@sym: s = ccode (f1, …, fn) ¶@sym: ccode (…, 'file', filename) ¶@sym: [c_stuff, h_stuff] = ccode (…, 'file', '') ¶Convert symbolic expression into C code.
Example:
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⎠ ⎠
ccode(g)
⇒ x*(x*(x*(1.0/3.0 - 1.0/4.0*x) - 1.0/2.0) + 1)
We can write to a file or obtain the contents directly:
[C, H] = ccode(g, 'file', '', 'show_header', false); C.name ⇒ file.c H.name ⇒ file.h
disp(H.code) -| #ifndef PROJECT__FILE__H -| #define PROJECT__FILE__H -| -| double myfun(double x); -| -| #endif
disp(C.code)
-| #include "file.h"
-| #include <math.h>
-|
-| double myfun(double x) {
-|
-| double myfun_result;
-| myfun_result = x*(x*(x*(1.0/3.0 - 1.0/4.0*x) - 1.0/2.0) + 1);
-| return myfun_result;
-|
-| }
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/fortran, @@sym/latex, @@ssym/function_handle.
Package: symbolic