How can I create an anonymous function from a symbolic matrix in MATLAB?

2 views (last 30 days)
I have a matrix of symbolic expressions, and I want to translate them into an anonymous function. How can I do this?

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 27 Jun 2009
You will need to convert between the Maple syntax and MATLAB syntax to create an anonymous function in MATLAB from a Maple symbolic matrix.. The following code creates a test symbolic matrix:
syms r l f
x = r*cos(l)*cos(f); y = r*cos(l)*sin(f); z = r*sin(l);
J = jacobian([x; y; z], [r l f])
The character string you create should begin with an open square bracket '[', and end with a closed square bracket ']'. Insert commas ',' between consecutive elements of the same row, and use semicolons ';' to end a row. Be aware that not all the syntax is the same from the symbolic functions in the Maple kernel to MATLAB functions, so you may have to translate between certain functions. An example is Maple's "arctan" function versus MATLABs "atan" function. You can use MATLABs STRREP function to translate between Maple and MATLAB functions which have the same function but different names.
The following is an example of how you could implement the translation between symbolic and character representation, when you have a symbolic matrix:
newstring = '[';
for i=1:M
for j=1:N
newstring = [newstring char(J(i,j)) ' '];
end
newstring = [newstring '; '];
end
newstring = newstring(1:end-3); %remove trailing punctuation
newstring = [newstring ']'];
You can use the EVAL function to create an anonymous function from the 'newstring' variable:
eval(['myfun = @(r,l,f) ' newstring])
You can now use MYFUN as a MATLAB function.

More Answers (0)

Categories

Find more on Symbolic Math Toolbox in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!