Anonymous functions provide a easy way to define a relatively simple function with one or more input arguments, parameters, and a single output argument. The anonymous function may be passed as an argument to other functions, but otherwise is only available in the workspace where it was defined.
Input arguments for anonymous functions
To create an anonymous function MATLAB uses
fname = @(arg1, arg2, arg3, ...) expression
There may be one or more input arguments specified in the parentheses after the @ character. The expression must produce a single object, which can be a scalar, vector, matrix or other more complicated structure.
h(u, v) = sin(3 u) cos(v + 4).
Define an anonymous function h with two input arguments.
Note the use of the elementwise operator .* so the function will work with input arguments which are arrays of the same size.
The names of the arguments does not matter, except within the expression defining the function. Thus an alternative definition for the function h is
Parameters which are not arguments
If the expression defining the anonymous function contains variables which are not arguments to the function, then the values of those variables when the function is defined are used.
The values of the variables a and b when the function is defined are used.
Define the variable a with value 2.
Define the anonymous function f using the current value of a, which is 2.
This calculates 32 = 9
Change the value of the variable a to 4.
The definition of the function f has not changed, so this still produces 9.
Warnings
- What happens if you try to define the anonymous function
f = @(v) sin(v), cos(v)
You will get the function f = @(v) sin(v) and the error message??? Undefined function or variable 'v'
(assuming the variable v is not defined). The definitionf = @(v) [sin(v), cos(v)]
will work producing a row vector with two elements. - The variable used for the name of the function is actually known as
a function handle. Try
f = @(v) sin(v);
whos f
Self-test Exercise
Write an anonymous function to calculate
decay(t) = cos(a t) e - b t
using- a = pi and b = 0.5, then
- a = 2 pi and b = 0.5,
Answer:
a = pi;
b = 0.5;
decay = @(t) cos(a*t) .* exp(-b*t)
a = 2*pi;
decay = @(t) cos(a*t) .* exp(-b*t)
Use the mouse to select the text between the word "Answer" and here to see the answer.
Summary
Anonymous functions are very useful for defining relatively simple functions which are used just within one MATLAB M-file. They can have several input arguments, including parameters whose values are determined when the function is defined, but one output argument which can be an array.