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.
% Function that calculates the perimeter of a rectangle func1 = @(a,b) 2 * (a + b);
% Call 'func1' p = func1(2,3);
p = 10
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);
y1 = 1
% Call 'func2' again y2 = func2(1);
y2 = 3
In the preceding code,
func2 is an anonymous function with a single input
x, whose expression also uses the variables
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);
y3 = 5
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.
I recommend the following books to learn more on functions in MATLAB.
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.
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.
- How to Define Functions in MATLAB
- How to Call a Function in MATLAB
- How to Add Help Documentation to a Function in MATLAB
- Local Functions in MATLAB
- Nested Functions in MATLAB
- Visibility of Nested Functions in MATLAB
- Private Functions in MATLAB
- Anonymous Functions in MATLAB
- Inside the Handle of Anonymous Functions in MATLAB
- Functions with Variable Input Arguments in MATLAB
- Functions with Variable Output Arguments in MATLAB
- How to Validate the Number of Input Arguments Passed to a Function in MATLAB
- How to Validate the Number of Output Arguments Passed to a Function in MATLAB
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.