How do I make a function from a symbolic expression in MATLAB?

Alireza picture Alireza · Jan 3, 2010 · Viewed 16.4k times · Source

How can I make a function from a symbolic expression? For example, I have the following:

syms beta
n1,n2,m,aa= Constants
u = sqrt(n2-beta^2);
w = sqrt(beta^2-n1);
a = tan(u)/w+tanh(w)/u;
b = tanh(u)/w;
f = (a+b)*cos(aa*u+m*pi)+a-b*sin(aa*u+m*pi);  %# The main expression

If I want to use f in a special program to find its zeroes, how can I convert f to a function? Or, what should I do to find the zeroes of f and such nested expressions?

Answer

gnovice picture gnovice · Jan 3, 2010

You have a couple of options...

Option #1: Automatically generate a function

If you have version 4.9 (R2007b+) or later of the Symbolic Toolbox you can convert a symbolic expression to an anonymous function or a function M-file using the matlabFunction function. An example from the documentation:

>> syms x y
>> r = sqrt(x^2 + y^2);
>> ht = matlabFunction(sin(r)/r)

ht = 

     @(x,y)sin(sqrt(x.^2+y.^2)).*1./sqrt(x.^2+y.^2)

Option #2: Generate a function by hand

Since you've already written a set of symbolic equations, you can simply cut and paste part of that code into a function. Here's what your above example would look like:

function output = f(beta,n1,n2,m,aa)
  u = sqrt(n2-beta.^2);
  w = sqrt(beta.^2-n1);
  a = tan(u)./w+tanh(w)./u;
  b = tanh(u)./w;
  output = (a+b).*cos(aa.*u+m.*pi)+(a-b).*sin(aa.*u+m.*pi);
end

When calling this function f you have to input the values of beta and the 4 constants and it will return the result of evaluating your main expression.


NOTE: Since you also mentioned wanting to find zeroes of f, you could try using the SOLVE function on your symbolic equation:

zeroValues = solve(f,'beta');