Function Handles & Callbacks
A function handle lets you treat a function as data. Anonymous Functions & Handles introduced the syntax; this lesson is about what you build with it: callbacks (code you hand to someone else to call later), dispatch tables, pipelines and event-style notifications.
Quick recap of the three ways to get a handle:
| Form | Example | Notes |
|---|---|---|
| Named function | h = @max |
Any built-in, path function, local or nested function |
| Anonymous function | h = @(x) x.^2 + 1 |
One expression; captures variables by value when created |
| Text to handle | h = str2func('max') |
Useful when the name comes from a file or settings |
What is a callback?
A callback is a function you pass to another function, which then decides when to call it. The caller stays in control of the details (what to print, where to store things) while the worker stays general. Here process_items knows nothing about printing; it just reports progress through whatever handle it receives:
items = [4 9 16 25];
process_items(items, @(k, n, r) fprintf('item %d of %d -> %g\n', k, n, r));
% A different callback: collect nothing, print only at the end
process_items(items, @quiet_progress);
function process_items(v, on_progress)
for k = 1:numel(v)
result = sqrt(v(k));
on_progress(k, numel(v), result); % hand control to the caller's code
end
end
function quiet_progress(k, n, ~)
if k == n
fprintf('done: %d items\n', n);
end
enditem 1 of 4 -> 2
item 2 of 4 -> 3
item 3 of 4 -> 4
item 4 of 4 -> 5
done: 4 items
The ~ in quiet_progress(k, n, ~) marks an input the callback accepts but ignores: every callback must accept the arguments its caller passes, even the ones it doesn't need.
Passing extra data to a callback
Callers often need the callback to know something extra: a threshold, a label, a file name. There are two common ways.
1. Capture it in an anonymous function. The extra value is copied into the handle when it is created:
limit = 10;
alert = @(name, value) check_limit(name, value, limit);
readings = struct('name', {'pump', 'fan', 'valve'}, 'value', {7, 12, 15});
for r = readings
alert(r.name, r.value);
end
function check_limit(name, value, limit)
if value > limit
fprintf('%s is over the limit (%g > %g)\n', name, value, limit);
end
endfan is over the limit (12 > 10)
valve is over the limit (15 > 10)
2. Use a cell array {@fn, extra1, extra2}. Graphics callbacks in MATLAB and Octave accept this form: the function is called with the standard arguments first (the source object and event data), followed by your extras. You can call such a callback yourself the same way:
cb = {@on_click, 'Save'};
feval(cb{1}, [], [], cb{2:end}); % what the graphics system does for you
function on_click(src, evt, label)
fprintf('clicked %s\n', label);
endclicked Save
In a real app it looks like this (an interactive figure, so not runnable here):
fig = figure;
uicontrol(fig, 'Style', 'pushbutton', 'String', 'Save', ...
'Callback', {@on_click, 'Save'}); % called as on_click(src, evt, 'Save')
set(fig, 'WindowButtonDownFcn', @(src, evt) disp('figure clicked'));Every graphics callback receives (src, evt): the object that triggered it and a structure (or object) with event details.
Dispatch tables
A struct (or containers.Map) whose values are handles replaces a long switch with a lookup. Adding a command is then a one-line change:
ops.add = @(a, b) a + b;
ops.sub = @(a, b) a - b;
ops.mul = @(a, b) a * b;
ops.pow = @power;
program = {'add', 2, 3; 'mul', 4, 5; 'pow', 2, 10; 'mod', 7, 3};
for k = 1:size(program, 1)
name = program{k, 1};
if isfield(ops, name)
fprintf('%s(%g, %g) = %g\n', name, program{k, 2}, program{k, 3}, ...
ops.(name)(program{k, 2}, program{k, 3}));
else
fprintf('unknown operation "%s"\n', name);
end
endadd(2, 3) = 5
mul(4, 5) = 20
pow(2, 10) = 1024
unknown operation "mod"
ops.(name) is a dynamic field reference (see Structures), and the (…) after it calls the handle stored there.
Composing functions
Because a handle is a value, you can write functions that take handles and return new ones:
compose = @(f, g) @(x) f(g(x));
half_then_round = compose(@round, @(x) x / 2);
disp(half_then_round([3 7 10]))
% A pipeline stored as a cell array of steps
steps = {@(v) v(v > 0), @sort, @(v) v * 10};
data = [3 -1 8 -5 2];
for k = 1:numel(steps)
data = steps{k}(data);
end
disp(data) 2 4 5
20 30 80
Callbacks inside built-in functions
Many numerical functions accept handles not only for the function to work on, but also for callbacks during the computation. A good example is an event function for the ODE solvers: ode45 calls it at every step and stops when its value crosses zero. Here a ball is dropped from 20 m, and the solver stops when its height reaches the ground:
opts = odeset('Events', @hit_ground);
[t, y, t_hit, y_hit] = ode45(@(t, y) [y(2); -9.81], [0 10], [20; 0], opts);
fprintf('hits the ground after %.3f s\n', t_hit);
fprintf('speed at impact: %.2f m/s\n', abs(y_hit(2)));
function [value, isterminal, direction] = hit_ground(t, y)
value = y(1); % height: an "event" happens when this is zero
isterminal = 1; % stop the integration at the event
direction = -1; % only while falling (value decreasing)
endhits the ground after 2.019 s
speed at impact: 19.81 m/s
Optimisers work the same way: optimset('OutputFcn', @my_monitor) makes fminsearch call my_monitor after each iteration, which is handy for logging or stopping early. More solver options are in Integration & ODEs and Roots & Minimization.
A simple notification list
Many programs need "tell everyone who is interested when something happens". You can build that from a cell array of handles. Each listener registers a callback; the notifier calls them all in order:
listeners = {};
listeners{end+1} = @(msg) fprintf('[log] %s\n', msg);
listeners{end+1} = @(msg) fprintf('[mail] would send: %s\n', upper(msg));
notify_all(listeners, 'backup finished');
notify_all(listeners(1), 'only the logger hears this');
function notify_all(callbacks, msg)
for k = 1:numel(callbacks)
callbacks{k}(msg);
end
end[log] backup finished
[mail] would send: BACKUP FINISHED
[log] only the logger hears this
MATLAB classes have built-in events and listeners for this pattern (events, notify, addlistener); the Handle Classes & Events lesson shows them, together with a version that also runs in Octave.
Inspecting handles
| Function | Returns |
|---|---|
func2str(h) |
The handle as text, e.g. '@(x) x + 1' or 'max' |
str2func(s) |
A handle from text |
isa(h, 'function_handle') |
true for any handle |
nargin(h) |
Number of declared inputs (for anonymous and M-file functions) |
feval(h, args...) |
Calls h; also accepts a function name as text |
f = @(a, b) a * b + 1;
fprintf('%s takes %d inputs\n', func2str(f), nargin(f));
g = str2func('@(s) [s ''!'']');
disp(g('hello'))
disp(isa(g, 'function_handle'))
disp(feval('max', [3 9 4]))
disp(isequal(@sin, @sin))@(a, b) a * b + 1 takes 2 inputs
hello!
1
9
1
The text from func2str is formatted differently: Octave keeps the spacing you typed, while MATLAB prints the compact form @(a,b)a*b+1. Two handles to the same named function compare equal; two separately created anonymous functions don't, even with identical text.
Things to watch out for
- An anonymous function captures copies. If it captures a huge matrix, that copy lives as long as the handle does.
- A callback must accept every argument its caller passes. Use
~for the ones you ignore. - Errors inside a callback surface in the code that called it. When a callback can fail, the caller should use
try/catchand report which callback broke (see Error Handling). - Handles to local functions work anywhere once created, even though the function's name is only visible in its file. That's how a file can hand out its private helpers.
Learn more: arrayfun & cellfun apply handles to every element; Local & Nested Functions shows handles that keep state.
Test yourself
What is a callback?
- A function that calls itself
- A function handle passed to other code, which calls it at the right moment
- A function that returns a handle
- A built-in debugger command
A button has 'Callback', {@on_click, 'Save'}. How is on_click called?
on_click('Save')on_click(src, evt, 'Save')on_click('Save', src, evt)on_click()
Why write function quiet_progress(k, n, ~)?
- To make the third input optional for callers
- To accept a third input that the function ignores
- To return nothing
- To mark the function as private