TExcelTAD
Home › MATLAB / Octave › Anonymous Functions & Handles

Anonymous Functions & Handles

A function handle is a value that refers to a function. You can store it in a variable, pass it to another function and call it later. Handles are created with the @ symbol, and they make it possible to write general tools like "integrate any function" or "apply any rule to every element".

Handles to named functions

Put @ in front of a function's name to get a handle. Calling the handle with parentheses calls the function:

matlab · try it yourself
f = @sqrt;
disp(f(49))
disp(class(f))
ops = {@min, @max, @mean};
data = [7 2 9 4];
for k = 1:numel(ops)
    fprintf('%s: %g\n', func2str(ops{k}), ops{k}(data));
end
7
function_handle
min: 2
max: 9
mean: 5.5

func2str converts a handle to text; str2func does the reverse.

Anonymous functions

An anonymous function is a one-expression function defined inline, without a file:

matlab
name = @(inputs) expression
matlab · try it yourself
sq = @(x) x.^2;
hyp = @(a, b) sqrt(a.^2 + b.^2);
isEven = @(n) mod(n, 2) == 0;
disp(sq(5))
disp(sq([1 2 3]))
disp(hyp(3, 4))
disp(isEven(1:6))
25
   1   4   9
5
  0  1  0  1  0  1

The body must be a single expression: no if, loops or assignments. Use element-wise operators so the function works on arrays, which many tools (plotting, integration) expect.

Capturing variables

An anonymous function can use variables from the workspace where it is created. Their values are captured (copied) at that moment; later changes don't affect it:

matlab · try it yourself
rate = 0.2;
withTax = @(p) p * (1 + rate);
disp(withTax(100))
rate = 0.5;              % changing rate afterwards...
disp(withTax(100))       % ...does not change the captured value
withTax = @(p) p * (1 + rate);   % re-create it to pick up the new value
disp(withTax(100))
120
120
150

This makes it easy to create functions with "parameters baked in":

matlab · try it yourself
make_line = @(m, c) @(x) m * x + c;     % a function that returns a function
f = make_line(2, 1);
g = make_line(-1, 10);
fprintf('f(3) = %g, g(3) = %g\n', f(3), g(3));
f(3) = 7, g(3) = 7

Passing functions to functions

Many built-ins take a function handle as input. A few examples (each gets a lesson of its own later):

Function Does what with the handle
fzero(f, x0) Finds where f(x) = 0
fminsearch(f, x0) Finds a minimum of f
integral(f, a, b) Integrates f from a to b
arrayfun(f, A) / cellfun(f, C) Applies f to each element
fplot(f, [a b]) Plots f over an interval
ode45(f, tspan, y0) Solves a differential equation
matlab · try it yourself
f = @(x) x.^3 - 2*x - 5;
root = fzero(f, 2);
fprintf('root of x^3 - 2x - 5: %.6f\n', root);
area = integral(@(x) exp(-x.^2), 0, 1);
fprintf('integral of exp(-x^2) on [0,1]: %.6f\n', area);
root of x^3 - 2x - 5: 2.094551
integral of exp(-x^2) on [0,1]: 0.746824

You can also write your own functions that accept handles:

matlab · try it yourself
apply_twice = @(fn, x) fn(fn(x));
disp(apply_twice(@(x) x + 3, 10))
disp(apply_twice(@sqrt, 16))
fprintf('%.4f\n', numeric_slope(@sin, 0));
fprintf('%.4f\n', numeric_slope(@(x) x.^2, 3));

function s = numeric_slope(f, x)
h = 1e-6;
s = (f(x + h) - f(x - h)) / (2 * h);
end
16
2
1.0000
6.0000

Handles to local functions

A handle can refer to a local function in a script, so you can pass a multi-line function wherever a handle is expected:

matlab · try it yourself
vals = arrayfun(@clamp01, [-0.5 0.3 1.7]);
disp(vals)

function y = clamp01(x)
if x < 0
    y = 0;
elseif x > 1
    y = 1;
else
    y = x;
end
end
        0   0.3000   1.0000

Test yourself

What does f = @(x) 2*x + 1; f(4) return?

  1. 8
  2. 9
  3. An error
  4. A function handle

After k = 3; g = @(x) k*x; k = 10;, what is g(2)?

  1. 6
  2. 20
  3. An error
  4. Depends on the version

Which of these can an anonymous function body contain?

  1. An if statement
  2. A for loop
  3. A single expression
  4. Several assignments