Documentation

matlabFunction

Convert symbolic expression to function handle or file

Syntax

  • g = matlabFunction(f)
    example
  • g = matlabFunction(f1,...,fN)
    example
  • g = matlabFunction(___,Name,Value)
    example

Description

example

g = matlabFunction(f) converts f to a MATLAB® function with the handle g. Here, f can be a symbolic expression, function, or a vector of symbolic expressions or functions.

example

g = matlabFunction(f1,...,fN) converts f1,...,fN to a MATLAB function with N outputs. The function handle is g. Each element of f1,...,fN can be a symbolic expression, function, or a vector of symbolic expressions or functions.

example

g = matlabFunction(___,Name,Value) converts symbolic expressions, functions, or vectors of symbolic expressions or functions to a MATLAB function using additional options specified by one or more Name,Value pair arguments. You can specify Name,Value after the input arguments used in the previous syntaxes.

Examples

Convert Symbolic Expression to Anonymous Function

Create the following symbolic expression r. Then convert sin(r)/r to a MATLAB function with the handle ht.

syms x y
r = sqrt(x^2 + y^2);
ht = matlabFunction(sin(r)/r)
ht = 
   @(x,y)sin(sqrt(x.^2+y.^2)).*1.0./sqrt(x.^2+y.^2)

Convert Several Symbolic Expressions to Anonymous Function

Create the following symbolic expression r. Then convert sin(r)/r and cos(r)/r to a MATLAB function with the handle ht.

syms x y
r = sqrt(x^2 + y^2);
ht = matlabFunction(sin(r)/r, cos(r)/r)
ht = 
    @(x,y)deal(sin(sqrt(x.^2+y.^2)).*1.0./sqrt(x.^2+y.^2),...
               cos(sqrt(x.^2+y.^2)).*1.0./sqrt(x.^2+y.^2))

Convert Symbolic Function to Anonymous Function

Create a symbolic function and convert it to a MATLAB function with the handle ht.

syms x y
f(x,y) = x^3 + y^3;
ht = matlabFunction(f)
ht = 
    @(x,y)x.^3+y.^3

Write Generated MATLAB Function to File

Convert a symbolic expression to a MATLAB function and write it to a file.

Create a symbolic expression.

syms x y z
r = x^2 + y^2 + z^2;

Convert r to a MATLAB function and write this function to a file called myfile. If myfile.m already exists in the current folder, matlabFunction replaces the existing function with the converted symbolic expression. You can open and edit the resulting file.

f = matlabFunction(log(r)+r^(-1/2),'File','myfile');
function out1 = myfile(x,y,z)
%MYFILE
%    OUT1 = MYFILE(X,Y,Z)
t2 = x.^2;
t3 = y.^2;
t4 = z.^2;
t5 = t2 + t3 + t4;
out1 = log(t5) + 1.0./sqrt(t5);

If a path to the file is an empty string, then matlabFunction does not create a file. It generates an anonymous function instead.

syms x y z
r = x^2 + y^2 + z^2;
f = matlabFunction(log(r)+r^(-1/2),'File','')
f = 
    @(x,y,z)log(x.^2+y.^2+z.^2)+1.0./sqrt(x.^2+y.^2+z.^2)

Disable Code Optimization

When you convert a symbolic expression to a MATLAB function and write the resulting function to a file, matlabFunction optimizes the code by default. This approach can help simplify and speed up further computations that use the file. However, generating the optimized code from some symbolic expressions and functions can be very time consuming. Use Optimize to disable code optimization.

Create a symbolic expression.

syms x
r = x^2*(x^2 + 1);

Convert r to a MATLAB function and write the function to the file myfile. By default, matlabFunction creates a file containing the optimized code.

f =  matlabFunction(r,'File','myfile');
function r = myfile(x)
%MYFILE
%    R = MYFILE(X)
t2 = x.^2;
r = t2.*(t2+1.0);

Disable the code optimization by setting the value of Optimize to false.

f =  matlabFunction(r,'File','myfile','Optimize',false);
function r = myfile(x)
%MYFILE
%    R = MYFILE(X)
r = x.^2.*(x.^2+1.0);

Generate Sparse Matrices

When you convert a symbolic matrix to a MATLAB function, matlabFunction represents it by a dense matrix by default. If most of the elements of the input symbolic matrix are zeros, the more efficient approach is to represent it by a sparse matrix.

Create a 3-by-3 symbolic diagonal matrix:

syms x
A = diag(x*ones(1,3))
A =
[ x, 0, 0]
[ 0, x, 0]
[ 0, 0, x]

Convert A to a MATLAB function representing a numeric matrix, and write the result to the file myfile1. By default, the generated MATLAB function creates the dense numeric matrix specifying each element of the matrix, including all zero elements.

f1 = matlabFunction(A,'File','myfile1');
function A = myfile1(x)
%MYFILE1
%    A = MYFILE1(X)
A = reshape([x,0.0,0.0,0.0,x,0.0,0.0,0.0,x],[3,3]);

Convert A to a MATLAB function setting Sparse to true. Now, the generated MATLAB function creates the sparse numeric matrix specifying only nonzero elements and assuming that all other elements are zeros.

f2 = matlabFunction(A,'File','myfile2','Sparse',true);
function A = myfile2(x)
%MYFILE2
%    A = MYFILE2(X)
A = sparse([1,2,3],[1,2,3],[x,x,x],3,3);

Specify Input Arguments for Generated Function

When converting an expression to a MATLAB function, you can specify the order of the input arguments of the resulting function. You also can specify that some input arguments are vectors instead of single variables.

Create a symbolic expression.

syms x y z
r = x + y/2 + z/3;

Convert r to a MATLAB function and write this function to the file myfile. By default, matlabFunction uses alphabetical order of input arguments when converting symbolic expressions.

matlabFunction(r,'File','myfile');
function r = myfile(x,y,z)
%MYFILE
%    R = MYFILE(X,Y,Z)
r = x+y.*(1.0./2.0)+z.*(1.0./3.0);

Use the Vars argument to specify the order of input arguments for the generated MATLAB function.

matlabFunction(r,'File','myfile','Vars',[y z x]);
function r = myfile(y,z,x)
%MYFILE
%    R = MYFILE(Y,Z,X)
r = x+y.*(1.0./2.0)+z.*(1.0./3.0);

Now, convert an expression r to a MATLAB function whose second input argument is a vector.

syms x y z t
r = (x + y/2 + z/3)*exp(-t);
matlabFunction(r,'File','myfile','Vars',{t,[x y z]});
function r = myfile(t,in2)
%MYFILE
%    R = MYFILE(T,IN2)
x = in2(:,1);
y = in2(:,2);
z = in2(:,3);
r = exp(-t).*(x+y.*(1.0./2.0)+z.*(1.0./3.0));

Specify Output Variables

When converting a symbolic expression to a MATLAB function, you can specify the names of the output variables. Note that matlabFunction without the File argument (or with a file path specified by an empty string) creates a function handle and ignores the Outputs flag.

Create symbolic expressions r and q.

syms x y z
r = x^2 + y^2 + z^2;
q = x^2 - y^2 - z^2;

Convert r and q to a MATLAB function and write the resulting function to a file myfile, which returns a vector of two elements, name1 and name2.

f = matlabFunction(r,q,'File','myfile',...
                   'Outputs',{'name1','name2'});
function [name1,name2] = myfile(x,y,z)
%MYFILE
%    [NAME1,NAME2] = MYFILE(X,Y,Z)
t2 = x.^2;
t3 = y.^2;
t4 = z.^2;
name1 = t2+t3+t4;
if nargout > 1
    name2 = t2-t3-t4;
end

Convert MuPAD Expression to MATLAB Function

You can convert MuPAD® expressions to MATLAB functions using the following two-step approach.

Use evalin to evaluate the MuPAD expression arcsin(x) + arccos(y) in the MATLAB Command Window.

syms x y
f = evalin(symengine, 'arcsin(x) + arccos(y)');

Now, use matlabFunction to convert the resulting expression to a MATLAB function. The file myfile contains the expression written in the MATLAB language.

matlabFunction(f,'File','myfile');
function f = myfile(x,y)
%MYFILE
%    F = MYFILE(X,Y)
f = asin(x) + acos(y);

Related Examples

Input Arguments

collapse all

f — Symbolic input to be converted to MATLAB functionsymbolic expression | symbolic function | symbolic vector | symbolic matrix

Symbolic input to be converted to a MATLAB function, specified as a symbolic expression, function, vector, or matrix. When converting sparse symbolic vectors or matrices, use the name-value pair argument 'Sparse',true.

f1,...,fN — Symbolic input to be converted to MATLAB function with N outputsseveral symbolic expressions | several symbolic functions | several symbolic vectors | several symbolic matrices

Symbolic input to be converted to MATLAB function with N outputs, specified as several symbolic expressions, functions, vectors, or matrices, separated by comma.

matlabFunction does not create a separate output argument for each element of a symbolic vector or matrix. For example, g = matlabFunction([x + 1, y + 1]) creates a MATLAB function with one output argument, while g = matlabFunction(x + 1, y + 1) creates a MATLAB function with two output arguments.

Name-Value Pair Arguments

Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and Value is the corresponding value. Name must appear inside single quotes (' '). You can specify several name and value pair arguments in any order as Name1,Value1,...,NameN,ValueN.

Example: matlabFunction(f,'File','myfile','Optimize',false)

'File' — Path to file containing generated MATLAB functionstring

Path to the file containing the generated MATLAB function, specified as a string. The generated function accepts arguments of type double, and can be used without Symbolic Math Toolbox™. If the value string is empty, matlabFunction generates an anonymous function. If the string does not end in .m, the function appends .m.

By default, matlabFunction with the File argument generates a file containing optimized code. Code optimization means that intermediate variables are used to simplify or speed up the code. MATLAB generates intermediate variables as a lowercase letter t followed by an automatically generated number, for example t32. To disable code optimization, use the Optimize argument.

See Write Generated MATLAB Function to File.

'Optimize' — Flag preventing optimization of code written to function filetrue (default) | false

Flag preventing optimization of code written to a function file, specified as false or true.

By default, matlabFunction with the File argument generates a file containing optimized code. Code optimization means that intermediate variables are used to simplify or speed up the code. MATLAB generates intermediate variables as a lowercase letter t followed by an automatically generated number, for example t32.

matlabFunction without the File argument (or with a file path specified by an empty string) creates a function handle. In this case, the code is not optimized. If you try to enforce code optimization by setting Optimize to true, then matlabFunction throws an error.

See Disable Code Optimization.

'Sparse' — Flag that switches between sparse and dense matrix generationfalse (default) | true

Flag that switches between sparse and dense matrix generation, specified as true or false. When you specify 'Sparse',true, the generated MATLAB function represents symbolic matrices by sparse numeric matrices. Use 'Sparse',true when you convert symbolic matrices containing many zero elements. Often, operations on sparse matrices are more efficient than the same operations on dense matrices.

See Generate Sparse Matrices.

'Vars' — Order of input variables or vectors in generated MATLAB functionstring | vector of symbolic variables | one-dimensional cell array of strings | one-dimensional cell array of symbolic variables | one-dimensional cell array of vectors of symbolic variables

Order of input variables or vectors in a generated MATLAB function, specified as a string, a vector of symbolic variables, or a one-dimensional cell array of strings, symbolic variables, or vectors of symbolic variables.

The number of specified input variables must equal or exceed the number of free variables in f. Do not use the same names for the input variables specified by Vars and the output variables specified by Outputs.

By default, when you convert symbolic expressions, the order is alphabetical. When you convert symbolic functions, their input arguments appear in front of other variables, and all other variables are sorted alphabetically.

See Specify Input Arguments for Generated Function

'Outputs' — Names of output variablesone-dimensional cell array of strings

Names of output variables, specified as a one-dimensional cell array of strings.

If you do not specify the output variable names, then they coincide with the names you use when calling matlabFunction. If you call matlabFunction using an expression instead of individual variables, the default names of output variables consist of the word out followed by a number, for example, out3.

Do not use the same names for the input variables specified by Vars and the output variables specified by Outputs.

matlabFunction without the File argument (or with a file path specified by an empty string) creates a function handle. In this case, matlabFunction ignores the Outputs flag.

See Specify Output Variables.

Output Arguments

collapse all

g — Function handle that can serve as input argument to numerical functionsMATLAB function handle

Function handle that can serve as an input argument to numerical functions, returned as a MATLAB function handle.

More About

collapse all

Tips

  • When you use the File argument, use rehash to make the generated function available immediately. rehash updates the MATLAB list of known files for directories on the search path.

  • To convert a MuPAD expression or function to a MATLAB symbolic expression, use f = evalin(symengine,'MuPAD_Expression') or f = feval(symengine,'MuPAD_Function',x1,...,xn). Then you can convert the resulting symbolic expression to a MATLAB function.

    matlabFunction cannot correctly convert some MuPAD expressions to MATLAB functions. These expressions do not trigger an error message. When converting a MuPAD expression or function that is not on the Differences Between MATLAB and MuPAD Syntax list, always check the conversion results. To verify the results, execute the resulting function.

Introduced in R2008b

Was this topic helpful?