Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 45 ยท Programming

Anonymous Functions and Function Handles

Learn the @ syntax for anonymous functions and function handles in MATLAB and Octave: closures, cellfun, arrayfun, feval, and passing handles to fzero and integral.

Sometimes you need a tiny function for one job: square a number, shift a curve, or tell fzero which equation to solve. Writing a whole function file for that would be heavy. MATLAB and Octave solve this with anonymous functions: small functions defined in one line, stored in a variable, with no file and no name of their own.

Closely related are function handles, which are values that point to a function so you can pass it around like data. Both use the @ symbol, and both are everywhere in numerical code. Here the real MATLAB/Octave code is shown read-only, and runnable Python lambdas reproduce the same ideas so you can experiment.

Two uses of the @ symbol

Anonymous @(x) x.^2 builds a new function on the spot.
Handle @sin points to a function that already exists.

Either way, you get a value you can store, pass and call.

1 / 2

The @ syntax

An anonymous function has the form @(inputs) expression. You usually assign it to a variable and then call it with parentheses, exactly like a regular function.

MATLAB
square = @(x) x.^2;
square(4)            % ans = 16
square([1 2 3])      % ans = 1 4 9

hyp = @(a, b) sqrt(a.^2 + b.^2);
hyp(3, 4)            % ans = 5

hello = @() disp('hi');   % no inputs: still call it with ()
hello()

Some rules worth remembering:

  • The body is one expression. You cannot put several statements, loops or if blocks inside it.
  • Use element-wise operators (.^, .*, ./) if the function should work on whole arrays, as explained in Arithmetic: Matrix vs Element-wise.
  • The function returns the value of the expression. There is no return keyword.
  • With no inputs you still write @() and still call it with (). Without the parentheses you only get the handle itself.
Python Python lambdas as a stand-in

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

This is a stand-in: Python's lambda plays the same role as @(x) .... In Python, ** on a NumPy array is already element-wise, whereas in MATLAB you must choose .^ over ^.

Function handles to existing functions

@name (without parentheses) creates a handle to a function that already exists, built in or your own.

MATLAB
f = @sin;
f(pi/2)              % ans = 1

g = @myhelper;       % handle to a function saved in myhelper.m
class(f)             % ans = function_handle
func2str(f)          % ans = sin

A handle is just a value. You can keep several in a cell array, return one from a function, or store it in a struct field. The calling style is the same as for the function itself, which makes handles the standard way to say "do this operation" to another function.

Closures: capturing variables

An anonymous function can use variables from the workspace where it is created. MATLAB copies their current values into the function at that moment. Changing the variable afterwards does not change the function.

MATLAB
a = 3;
line1 = @(x) a*x + 1;
line1(2)             % ans = 7

a = 100;             % too late: line1 kept a = 3
line1(2)             % ans = 7 (still)

This capturing is called a closure. It lets you build a family of functions from one template, and it lets you turn a function with extra parameters into a function of one variable, which is exactly what solvers expect.

MATLAB
poly = @(x, c) c(1)*x.^2 + c(2)*x + c(3);
coeffs = [1 -3 2];
p = @(x) poly(x, coeffs);   % parameters frozen in; p takes only x
p(5)                        % ans = 12
Python Closures freeze values at creation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The stand-in shows an honest difference. MATLAB always freezes captured values at definition time. Plain Python lambdas look the variable up when they are called, so we copy the value with a default argument to imitate MATLAB.

If you use a variable inside an anonymous function and it does not exist yet at definition time, MATLAB reports an undefined-variable error when you create the function, not when you call it.

Applying functions to many elements

Handles shine when you hand them to functions that apply an operation repeatedly.

  • arrayfun(f, A) calls f on each element of a numeric array.
  • cellfun(f, C) calls f on each cell of a cell array (see Cell Arrays).
  • By default both require each call to return a scalar. For anything else, add 'UniformOutput', false and you get a cell array back.
MATLAB
arrayfun(@(k) k^2, 1:5)                  % 1 4 9 16 25

words = {'apple', 'fig', 'banana'};
cellfun(@numel, words)                   % 5 3 6
cellfun(@upper, words, 'UniformOutput', false)
% {'APPLE', 'FIG', 'BANANA'}

Before reaching for these, check whether a vectorized expression does the job. (1:5).^2 is shorter and much faster than arrayfun. Save arrayfun and cellfun for cases where the operation cannot be written with array operators. More on that in Vectorization.

Python map-style stand-ins for arrayfun and cellfun

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Calling a handle by name and with feval

If you hold the function as a handle, f(x) is enough. The function feval also runs a function given as a handle or as a name string:

MATLAB
feval(@sin, pi/2)    % ans = 1
feval('cos', 0)      % ans = 1

feval is handy when the function name is chosen at run time, for instance from a menu or a configuration file. For everyday code, prefer a handle and call it directly.

Passing functions to solvers

Numerical routines such as fzero (find a root), integral (area under a curve) and fminsearch (minimize) take a function as an input. An anonymous function is the natural way to provide one.

MATLAB
% Where does x^3 - 2x - 5 cross zero, starting near 2?
root = fzero(@(x) x.^3 - 2*x - 5, 2);   % about 2.0946

% Area under sin(x) from 0 to pi
area = integral(@sin, 0, pi);            % about 2

% Same integral, but with a parameter captured from the workspace
k = 3;
area_k = integral(@(x) sin(k*x).^2, 0, pi);  % about pi/2

Closures solve the "extra parameter" problem: the solver only passes x, and your anonymous function brings along k from the workspace. The full toolkit is covered in Solving Equations and Optimization and Integration, Differentiation and ODEs.

Python Stand-ins with scipy: fzero and integral

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Here SciPy's brentq needs an interval whose ends have opposite signs, while MATLAB's fzero can start from a single guess. The rest of the pattern, passing a function plus extra parameters through a closure, is identical.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does f = @(x) x.^2 + 1; create?

    The @(x) part defines the input; the expression after it becomes the body. Nothing is computed until you call f(...), and x is the function's own input, so it does not need to exist beforehand.
  2. 2. After a = 2; g = @(x) a*x; a = 50; what does g(3) return?

    An anonymous function copies the values of the workspace variables it uses at the moment it is created. g keeps a = 2, so g(3) is 6.
  3. 3. Which call is valid for applying a function to each cell of C and getting a cell array of non-scalar results?

    cellfun expects scalar results unless you pass 'UniformOutput', false, which collects each result in a cell instead.
  4. 4. Why is an anonymous function a good fit for fzero(@(x) x.^2 - c, 1) when c is a workspace variable?

    Solvers call your function with just the unknown. A closure captures the extra parameter c at definition time so the function still looks like a function of one variable.

Summary

  • @(inputs) expression builds an anonymous function from a single expression; call it like any function.
  • @name makes a handle to an existing function; func2str and class show what it is.
  • Anonymous functions capture workspace values when created, which is called a closure.
  • arrayfun and cellfun apply a handle to many elements; add 'UniformOutput', false for non-scalar results, and prefer vectorized code when it exists.
  • feval calls a function by handle or name; solvers like fzero and integral take handles.
  • In this lesson MATLAB code is read-only, and Python lambdas are honest stand-ins for the ideas.

Next, learn how to deal with problems in Errors, Warnings and Debugging.