MATLAB: How to convert a symbolic expression to one suited for use by the ODExx commands in Symbolic toolbox 3.2.3 (R2008a)

automatic;charconversiondifferentialequationmathMATLABodeordinarysymbolicSymbolic Math Toolbox

I have a system of ODEs that were generated by the Symbolic Math Toolbox. I would like a function similar to SYM2POLY command except for ODEs instead of polynomials.

Best Answer

You can convert the symbolic expressions to MATLAB strings using the CHAR command. Then you can utilize MATLAB string processing functions to replace the symbolic variable strings with state variables that are used in the ODE solvers.
% Note that I am assuming that your symbolic results are stored in a variable. You should be able to convert that symbolic result to a string using the CHAR command. For example str=char(__your_symbolic_variable_here__);
% The following is present just for example purposes.
str=strvcat('dL1 = 10*sin(a1)*cos(a1)*z1*z2+5*sin(a1)^2-5*sin(a1)^2*z1^2;',...
'dL2 = -10*sin(a1)*cos(a1)*z1*z2+5*cos(a1)^2-5*cos(a1)^2*z1^2',...
'da1 = 10*z1*z2-10*z1*z2*sin(a1)^2+1+5*sin(a1)*cos(a1)-5*sin(a1)*cos(a1)*z1^2;',...
'dz1 = z2;',...
'dz2 = 5 * (1 - z1^2) * z2 - z1 + 5 * cos(2.466 * t);');
% You will need to construct a "table" variable. This is a cell array with the first column the string to search for and the second
% column is the string to replace the instances of the first column.
table={'dL1','dx(1)';...
'dL2','dx(2)';...
'da1','dx(3)';...
'a1','x(3)';...
'dz1','dx(4)';...
'z1','x(4)';...
'dz2','dx(5)';...
'z2','x(5)'...
};
syms2mcode('Polx5.m',str,table);% this function is an attachment
The SYMS2MCODE.m function is attached below.