MATLAB - Function Handles
MATLAB - Modern Usage of Function Handles
Section titled “MATLAB - Modern Usage of 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.
Why Use Function Handles?
Section titled “Why Use Function Handles?”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
.mfile. - Capturing Workspace Variables: Anonymous functions can ‘capture’ the state of variables at the time of their creation, a concept known as a closure.
Creating Function Handles
Section titled “Creating Function Handles”You create a function handle using the @ operator.
1. Handle to a Named Function
Section titled “1. Handle to a Named Function”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 functionpower_handle = @calculatePower;
% Use the handle to call the functionresult = power_handle(10, 2); % result will be 100disp(result);2. Handle to an Anonymous Function
Section titled “2. Handle to an Anonymous Function”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.2disp(result);
% An anonymous function with multiple inputsadd_handle = @(a, b) a + b;sum_result = add_handle(10, 32); % sum_result will be 42disp(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 rootinitial_guess = 2;
% 3. Pass the function handle and guess to fzerox_root = fzero(my_function, initial_guess);
% 4. Display the result and verifydisp(['The root of cos(x) near x=2 is: ', num2str(x_root)]);disp(['cos(root) is: ', num2str(cos(x_root))]); % Should be close to 0The output will be:
The root of cos(x) near x=2 is: 1.5708cos(root) is: -7.3464e-17This 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.
Example: A Generic Power Function Factory
Section titled “Example: A Generic Power Function Factory”% 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 handlesresult_sq = square(5); % result is 25result_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.
Function Handles vs. Strings (Legacy)
Section titled “Function Handles vs. Strings (Legacy)”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.