str2func

Creates a function handle from text.

Category: Language Fundamentals > Data Types

Syntax

fh = str2func(str)

Builds a handle from a function name or from the text of an anonymous function.

Description

str2func is the inverse of func2str. It is useful when the function to call comes from data, such as a name read from a file or typed by a user. A handle created from an anonymous function text is built in a fresh workspace, so it cannot capture variables from the caller.

Because the text of an anonymous function is parsed and evaluated, only use it with trusted input.

Input arguments

str
Name of a function, such as 'sin', or text starting with @, such as '@(x) x.^2'.

Output arguments

fh
Function handle that can be called like any other.

Example

Anonymous and named functions

f = str2func('@(x) x.^2 + 1');
f(3)
g = str2func('sin');
g(0)
Output
ans = 10
ans = 0

See also

func2str feval cellfun arrayfun