Skip to content

MATLAB - Function Handles

Function handles are a fundamental data type in MATLAB that allow you to treat functions as variables. You can pass them as arguments to other functions, store them in data structures, and call them indirectly. This enables powerful programming patterns, such as creating function-driven tools and customizing built-in MATLAB algorithms.

Function handles are essential for:

  • Passing Functions to Functions: The primary use case. Functions like numerical solvers (fzero), optimizers (fminsearch), and integrators (integral) require you to pass in the function they need to operate on.
  • Callback Functions: In GUI programming (with App Designer) or data acquisition, you use function handles to define what code runs in response to an event (e.g., a button click).
  • Anonymous (Inline) Functions: Creating lightweight, single-expression functions without needing a separate .m file.
  • Capturing Workspace Variables: Anonymous functions can ‘capture’ the state of variables at the time of their creation, a concept known as a closure.

You create a function handle using the @ operator.

If you have a function defined in a file (e.g., my_function.m) or as a local function within a script, you can create a handle to it.

% --- Assume this function is in a file named 'calculatePower.m' on the MATLAB path ---
% function y = calculatePower(x, n)
% y = x.^n;
% end
% Create a handle to the named function
power_handle = @calculatePower;
% Use the handle to call the function
result = power_handle(10, 2); % result will be 100
disp(result);

Anonymous functions are ideal for simple, one-line expressions. They are defined directly in your code and are not stored in a file.

% Syntax: handle = @(input1, input2, ...) expression
hyperbola = @(x) 1./x;
result = hyperbola(5); % result will be 0.2
disp(result);
% An anonymous function with multiple inputs
add_handle = @(a, b) a + b;
sum_result = add_handle(10, 32); % sum_result will be 42
disp(sum_result);

Practical Application: Passing Handles to MATLAB Solvers

Section titled “Practical Application: Passing Handles to MATLAB Solvers”

A classic application is finding the root of a mathematical function using fzero. fzero needs to know which function to solve.

Example: Finding the Root of cos(x) near x=2

Section titled “Example: Finding the Root of cos(x) near x=2”
% 1. Define the function for which we want to find a root (where f(x) = 0)
my_function = @(x) cos(x);
% 2. Provide an a initial guess for the location of the root
initial_guess = 2;
% 3. Pass the function handle and guess to fzero
x_root = fzero(my_function, initial_guess);
% 4. Display the result and verify
disp(['The root of cos(x) near x=2 is: ', num2str(x_root)]);
disp(['cos(root) is: ', num2str(cos(x_root))]); % Should be close to 0

The output will be:

The root of cos(x) near x=2 is: 1.5708
cos(root) is: -7.3464e-17

This demonstrates how fzero uses the my_function handle to repeatedly evaluate cos(x) until it finds the value of x that makes it zero.

Advanced Topic: Closures (Capturing Variables)

Section titled “Advanced Topic: Closures (Capturing Variables)”

Anonymous functions can capture variables from their parent workspace. This is useful for creating parameterized functions.

% This script creates a function handle that is parameterized by 'n'
function f_handle = makePowerFunction(n)
% 'n' is captured from the workspace of makePowerFunction
f_handle = @(x) x.^n;
end
% --- In the command window or another script ---
% Create a function that squares numbers (n=2)
square = makePowerFunction(2);
% Create a function that cubes numbers (n=3)
cube = makePowerFunction(3);
% Use the specialized function handles
result_sq = square(5); % result is 25
result_cu = cube(5); % result is 125
disp(['5 squared is: ', num2str(result_sq)]);
disp(['5 cubed is: ', num2str(result_cu)]);

Here, square is a function handle that ‘remembers’ that n=2, and cube ‘remembers’ that n=3. This is a powerful technique for creating reusable, configurable code.

In older MATLAB versions, it was common to pass function names as strings (e.g., fzero('cos', 2)). This practice is strongly discouraged now.

  • Robustness: Function handles are checked by MATLAB when created, preventing errors from typos. Strings are evaluated at run-time, making errors harder to find.
  • Performance: Calling a function via a handle is significantly faster than evaluating a string.
  • Scope: Function handles work correctly with local and private functions, whereas strings do not.

Best Practice: Always use the @ operator to create function handles. Avoid passing function names as character vectors.