matlabFunction

Converts a symbolic expression into an ordinary function handle.

Category: Symbolic Computations in MATLAB > Conversion Between Symbolic and Numeric

Syntax

f = matlabFunction(s)

Function handle with the symbolic variables of s as arguments, in alphabetical order.

f = matlabFunction(s, 'Vars', v)

Fixes the arguments and their order with the variables in v.

Description

The expression is turned into numeric code so it can be evaluated quickly in loops, plots or solvers such as fzero and ode45, without symbolic overhead. Operators such as *, / and ^ are written in their elementwise forms (.*, ./, .^), so the handle works on vectors.

With several variables the argument order is alphabetical unless 'Vars' is given. A symbolic vector or matrix gives a handle that returns an array of the same shape.

Input arguments

s
Symbolic expression or array of expressions.
'Vars'
Vector or cell array of symbolic variables that become the inputs of the function.

Output arguments

f
Function handle that evaluates the expression numerically and accepts arrays elementwise.

Example

Evaluate on a vector and fix the argument order

syms x y
f = matlabFunction(x^2 + 1);
f(1:3)
g = matlabFunction(x + 2*y, 'Vars', [y x]);
g(1, 10)
func2str(f)
Output
ans = 1×3

     2     5    10
ans = 12
ans = '@(x)(x.^2)+1'

Notes

Other options of the MATLAB function, such as writing the code to a file, are not supported.

See also

subs vpa fzero func2str sym