Anonymous Functions
Anonymous Functions.
Description
Anonymous functions provide a convenient way to swiftly create straightforward functions without the need to generate separate M-files on every occasion.
These anonymous functions can be built either directly at the command line or within any M-file function or script.
To create an anonymous function from an expression, use the following syntax:
function_handle = @(argument_list) expression
Breaking down this syntax, expression represents the body of the function, which contains the code that performs the primary task of your function.
This part consists of a valid expression. Next, there's argument_list, which is a comma-separated list of input arguments to be passed to the function.
These components are similar to the body and argument list of any regular function.
At the beginning of this syntax statement, you'll notice the @ sign.
This @ sign is the operator that constructs a function handle.
Creating a function handle for an anonymous function allows you to invoke the function and is useful when passing your anonymous function as an argument to another function.
The @ sign is a necessary part of the anonymous function definition.
It's worth noting that function handles not only apply to anonymous functions but also to any function.
The syntax for creating a function handle to a regular function is different and looks like this:
function_handle = @function_name
For example: f = @cos
You have the option to store function handles along with their associated values in a MAT-file.
Later, in a different session, you can retrieve and utilize them using the save and load functions.
for example a = 1;b = 2; f = @(x) a + b + x; save('test.nH5', f);
Only .nh5 files allows to save and load function_handle type as expected.
You can create an anonymous function that takes multiple input arguments, x and y.
Assuming that variables A and B are already defined, you can define the function as follows:
A = 10; B = 100; r = @(x, y) (A*y + B*x);
Examples
Multiple input arguments
Save/Load function handle
Multiple output arguments
See also
func2str, str2func, isfunction_handle.
History
1.0.0
initial version
Author
Allan CORNET
Last updated