What is the difference between an anonymous function and a function handle in MATLAB?

120 views Asked by At

I hear these two terms, anonymous function and function handle being used to refer to something like f = @(x) x.^2 in MATLAB. But then I've also heard that these terms mean different things. How do these two terms differ?

1

There are 1 answers

2
Cris Luengo On

A function handle is a reference to a function. For example, @sin is a handle to the function sin. This is a variable that can be evaluated as if it were a function, but it can also be passed to another function as an argument. For example:

integral(@sin, 0, 1)

Here we pass the function sin as an argument to integral. We need the special syntax @sin to do so, because in MATLAB sin by itself is the same thing as sin(), that is, we call the function with no arguments.

So

f = @sin

makes the variable f refer to the function sin. f is a function handle.

An anonymous function is a function with no name. This concept is called "lambda expression" or "function literal" in some other languages. @(x) x.^2 is an anonymous function. We cannot refer to it by its name, as we do with other functions, so we can only refer to it by its handle. So this expression returns a handle to the newly created anonymous function.

Thus, the expression

f = @(x) x.^2

both creates an anonymous function, and makes f a function handle that refers to that anonymous function.


Note 1

In MATLAB, the anonymous function is also a closure. That is, it captures the environment in which it is defined. For example:

a = 5;
f = @(x) a * x.^2;

Here, the anonymous function referenced by f holds the expression that will be evaluated when the function is called, a * x.^2, as well as the definition of the variable a when this anonymous function was called. We can now safely delete the variable a, and still evaluate f.


Note 2

A function handle in MATLAB references not a specific instance of a function, but all of the overloaded functions with the same name as well. When calling the function referenced by the handle, the normal overload resolution applies. But the overload resolution happens in the context where the function handle was created, and so the function handle can refer to some private function that was visible when the handle was created, but not visible at the point where it is evaluated.


Note 3

Don’t do @(x) sin(x). This is functionally identical to @sin, but adds a layer of indirection: when called, the anonymous function must be evaluated. This means that MATLAB must create a workspace for the anonymous function, and destroy it when it’s done. This takes time. The overhead of calling a function is one of the few remaining inefficiencies in the MATLAB interpreter.


For more details, see the MATLAB documentation on Function Handles and Anonymous Functions.