matlabFunction

Convert symbolic expression to function handle or file

Syntax

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

Description

example

````g = matlabFunction(f)` converts the symbolic expression or function `f` to a MATLAB® function with handle `g`. If there is an equivalent MATLAB function operating on `double` data type for the symbolic expression or function, then the converted function can be used without Symbolic Math Toolbox™.```

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)` uses 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

collapse all

Convert the symbolic expression `r` to a MATLAB function with the handle `ht`. The converted function can be used without Symbolic Math Toolbox.

```syms x y r = sqrt(x^2 + y^2); ht = matlabFunction(r)```
```ht = function_handle with value: @(x,y)sqrt(x.^2+y.^2)```

Convert multiple symbolic expressions using comma-separated input.

`ht = matlabFunction(r, r^2)`
```ht = function_handle with value: @(x,y)deal(sqrt(x.^2+y.^2),x.^2+y.^2)```

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 = function_handle with value: @(x,y)x.^3+y.^3```

Write the generated MATLAB function to a file by specifying the `File` option. Existing files are overwritten. When writing to a file, `matlabFunction` optimizes the code using intermediate variables named `t0`, `t1`, …. Include comments in the file by using the `Comments` option.

Write the MATLAB function generated from `f` to the file `myfile`.

```syms x f = x^2 + log(x^2); matlabFunction(f,'File','myfile');```
```function f = myfile(x) %MYFILE % F = MYFILE(X) % This function was generated by the Symbolic Math Toolbox version 8.4. % 01-Sep-2019 00:00:00 t2 = x.^2; f = t2+log(t2);```

Include the comment `Version: 1.1` in the file.

`matlabFunction(f,'File','myfile','Comments','Version: 1.1')`
```function f = myfile(x) ... %Version: 1.1 t2 = x.^2; ...```

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 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);```

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 by 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);```

When converting an expression to a MATLAB function, you can specify the order of the input arguments of the resulting function. You can also specify that some input arguments are vectors instead of scalar 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 that contain only lowercase letters for the variable names. The generated input arguments are scalar variables `x`, `y`, and `z`.

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

Specify the `Vars` argument as the vector ```[y z x]``` to modify the order of input arguments for the generated MATLAB function. The generated input arguments are scalar variables `y`, `z`, and `x`.

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

Now, convert an expression `r` to a MATLAB function whose input arguments are a scalar and a vector. Specify the `Vars` argument as the cell array `{t,[y z x]}`. The generated input arguments are a scalar variable `t` and a 1-by-3 vector variable `in2`.

```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./2.0+z./3.0);```

To generate a MATLAB function with input arguments that are vector variables, specify the name-value argument `Vars` as a cell array.

Create a symbolic expression that finds the dot product of two 1-by-3 vectors.

```syms x y [1 3] real f = dot(x,y);```

Convert the expression `f` to a MATLAB function. Specify `Vars` as a cell array `{x,y}`. The generated input arguments are two 1-by-3 vector variables `in1` and `in2` that correspond to `x` and `y`, respectively.

`matlabFunction(f,'File','myfile','Vars',{x,y});`
```function f = myfile(in1,in2) %MYFILE % F = MYFILE(IN1,IN2) x1 = in1(:,1); x2 = in1(:,2); x3 = in1(:,3); y1 = in2(:,1); y2 = in2(:,2); y3 = in2(:,3); f = x1.*y1+x2.*y2+x3.*y3;```

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 character vector) 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```

You can speed up the evaluation of a symbolic function at given coordinates by converting the symbolic function to an anonymous MATLAB® function. Use `matlabFunction` to perform the conversion. Evaluation of a symbolic function returns symbolic numbers that are precise, while evaluation of a MATLAB function returns double-precision numbers.

Create a symbolic function `f(x,y,z)` that is a function of `x`, `y`, and `z`.

```syms f(x,y,z) f(x,y,z) = y*z*sin(x) + x*sin(z)*cos(y) - z^3;```

Create 3-D grid coordinates at the specified intervals.

`[xDouble,yDouble,zDouble] = meshgrid(1:20,1:50,1:20);`

Evaluate the symbolic function at these coordinates. Measure the elapsed time using a pair of `tic` and `toc` calls.

```tic fResult = f(xDouble,yDouble,zDouble); toc```
```Elapsed time is 1.357873 seconds. ```

Here, evaluation is slow, but it returns symbolic numbers that are precise. Show a sample of the results.

`fResult(1:2,1:2,20)`
```ans =  $\left(\begin{array}{cc}20 \mathrm{sin}\left(1\right)+\mathrm{cos}\left(1\right) \mathrm{sin}\left(20\right)-8000& 20 \mathrm{sin}\left(2\right)+2 \mathrm{cos}\left(1\right) \mathrm{sin}\left(20\right)-8000\\ 40 \mathrm{sin}\left(1\right)+\mathrm{cos}\left(2\right) \mathrm{sin}\left(20\right)-8000& 40 \mathrm{sin}\left(2\right)+2 \mathrm{cos}\left(2\right) \mathrm{sin}\left(20\right)-8000\end{array}\right)$```

To speed up the evaluation of the function, convert the symbolic function to a MATLAB function using `matlabFunction`. Evaluate the MATLAB function at the same coordinates.

```f1 = matlabFunction(f); tic fResult = f1(xDouble,yDouble,zDouble); toc```
```Elapsed time is 0.010034 seconds. ```

Here, evaluation is faster. The evaluated MATLAB function returns double-precision numbers. Show a sample of the results.

`fResult(1:2,1:2,20)`
```ans = 2×2 103 × -7.9827 -7.9808 -7.9667 -7.9644 ```

Input Arguments

collapse all

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`.

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 Arguments

Specify optional pairs of arguments as `Name1=Value1,...,NameN=ValueN`, where `Name` is the argument name and `Value` is the corresponding value. Name-value arguments must appear after other arguments, but the order of the pairs does not matter.

Before R2021a, use commas to separate each name and value, and enclose `Name` in quotes.

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

Comments to include in the file header, specified as a character vector, cell array of character vectors, or string vector.

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

When writing to a file, `matlabFunction` optimizes the code using intermediate variables named `t0`, `t1`, .... To disable code optimization, use the `Optimize` argument.

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

When writing to a file, `ccode` optimizes the code using intermediate variables named `t0`, `t1`, ....

`matlabFunction` without the `File` argument (or with a file path specified by an empty character vector) 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.

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.

Order of input variables or vectors in a generated MATLAB function, specified as a character vector, a vector of symbolic variables, or a one-dimensional cell array of character vectors, 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 that contain only lowercase letters for the variable names, 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.

Specify `Vars` as a vector to generate a MATLAB function with input arguments that are scalar variables. Specify `Vars` as a cell array to generate a MATLAB function with input arguments that are a combination of scalar and vector variables.

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

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 character vector) creates a function handle. In this case, `matlabFunction` ignores the `Outputs` flag.

Output Arguments

collapse all

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

Limitations

• Some symbolic functions that have no corresponding MATLAB functions operating on `double` data type, such as `simplify` and `solve`, are kept as symbolic functions in the converted MATLAB function handle or file. The converted file that consists of these functions cannot be deployed using MATLAB Coder™ or MATLAB Compiler™. You need to create your own functions with `double` data type to replace these symbolic functions. If you are interested in a symbolic function that cannot be deployed, please contact MathWorks Technical Support.

Version History

Introduced in R2008b