|
FreeMat
|
Section: Functions and Scripts
The str2func function converts a function name into a function pointer. The syntax is
y = str2func('funcname')
where funcname is the name of the function. The return variable y is a function handle that points to the given function.
An alternate syntax is used to construct an anonymous function given an expression. They syntax is
y = str2func('anonymous def')
where anonymous def is an expression that defines an anonymous function, for example '@(x) x.^2'.
Here is a simple example of using str2func.
--> sin(.5) % Calling the function directly
ans =
0.4794
--> y = str2func('sin') % Convert it into a function handle
y =
@sin
--> y(.5) % Calling 'sin' via the function handle
ans =
0.4794
Here we use str2func to define an anonymous function
--> y = str2func('@(x) x.^2')
y =
@(x) x.^2
--> y(2)
ans =
4