Tutorial

Inside the Handle of Anonymous Functions in MATLAB

The handle of an anonymous function is a variable of type function_handle and it is used to call the function.

Description

An anonymous function is defined using the syntax h = @(input1,…,inputN) expression, where h is the function handle, input1,…,inputN is the set of inputs, and expression is a single executable statement.

These functions are called as any other function, but using the corresponding function handle.

Learn more on anonymous functions here.
% Function that calculates the perimeter of a rectangle
func1 = @(a,b) 2 * (a + b);
% Call 'func1'
p = func1(2,3);

Function handle

The function handle of an anonymous function is a variable of type function_handle. It stores the expression and the variables necessary to evaluate the expression.

If the expression of an anonymous function uses variables that are not in the set of input arguments, but they exist in the workspace when the function is created, MATLAB stores a copy of these variables in the function handle.

% Function that evaluates the line 'y = 2x + 1'
m = 2; n = 1;
func2 = @(x) m*x + n;
% Call 'func2'
y1 = func2(0);
% Call 'func2' again
y2 = func2(1);

In the preceding code, func2 is an anonymous function with a single input x, whose expression also uses the variables m and n existing in the workspace. Note that the handle stores a copy of these variables, so they persist even if the original variables are cleared.

% Clear the variables 'm' and 'n', and call 'func2' again
clearvars('m','n');
y3 = func2(2);

Once a handle to an anonymous function is created, its variables cannot be updated. You need to create a new handle to use a different set of values.

Further reading

I recommend the following books to learn more on functions in MATLAB.

  1. MATLAB: A Practical Introduction to Programming and Problem Solving (4th Edition)

    This book was the winner of a Textbook Excellence Award. The sixth chapter covers user-defined functions, scope of variables, debugging, and other aspects related to the development of MATLAB programs.

  2. MATLAB for Engineers (5th Edition)

    This excellent book is especially oriented to engineers and scientists who want to learn MATLAB programming. Chapter 6 explains how to create functions, including anonymous functions, local functions, and nested functions.

I also recommend the following page in the MATLAB help documentation, and the other tutorials in this series.

web(fullfile(docroot, 'matlab/matlab_prog/anonymous-functions.html'));

Source code

I hope you have understood the details inherent to the handle of anonymous functions in MATLAB. The source code developed in this tutorial is available at this page.

Share

Your friends may need this knowledge to complete a task. Share this tutorial.