ABSTRACT

A function handle (@) is a reference to a function that can be treated as a variable. It can be copied, placed in cell array, and evaluated just like a regular function. For example,

f = @sqrt

f(2)

sqrt(2)

“8primer” — #84

The str2func function converts a string to a function handle. For example,

f = str2func(’sqrt’)

f(2)

Function handles can refer to built-in MATLAB functions, to your own function in an M-file, or to anonymous functions. An anonymous function is defined with a one-line expression, rather than by an M-file. Try:

g = @(x) x^2-5*x+6-sin(9*x)

g(1)

Some MATLAB functions that operate on function handles need to evaluate the function on a vector, so it is often better to define an anonymous function (or M-file) so that it can operate entry-wise on scalars, vectors, or matrices. Try this instead:

g = @(x) x.^2-5*x+6-sin(9*x)

g([0 1])

The general syntax for an anonymous function is

handle = @(arg1, arg2, ...) expression

Here is an example with two input arguments, which computes the 2-norm of a vector of length 2.