6.6: Anonymous (or In-Line) Functions
- Page ID
- 55660
A MATLAB "anonymous" (or in-line) function is a one-liner with a single output and multiple inputs that can be defined directly in the command window or indeed on the fly in any program (possibly another function). An anonymous function has a very important property: any variables not defined as inputs will be assigned the current values - at the time the anonymous function is created - within the "variable space" (e.g., workspace) of the calling program (e.g., command window).
We provide a concrete example. In particular, we define an anonymous function
p = 2; x_to_the_2p_anon = @(x) x_to_the_2p(x,p);
which is identical to \(\mathrm{x}_{-}\)to_the_2p but now a function of single variable, \(\mathrm{x}\), rather than two variables. The value of \(p\) is frozen to 2 , though of course more generally we can replace \(p=2\) with any expression by which to evaluate \(p\) in terms of other variables.
To call our anonymous function, we do (following the definition above):
>> x_to_the_2p_anon([1,2])
ans =
1 16
>>
The above appears rather pointless, but it serves an important role in passing functions to other functions - in particular in the context of MATLAB in which there are many built-in’s that require function inputs of a particular form.
Let’s say that we wish to apply our function \(f_{-} o_{-}\)diff to our function \(x_{-}\)to_the_2p. But f_o_diff is expecting a function of a single input, \(x\), whereas x_to_the_2p has two inputs — and two necessary inputs, since without p we can not evaluate x_to_the_2p. This conundrum is easily resolved with inline functions:
>> p = 2; >> x_to_the_2p_anon = @(x) x_to_the_2p(x,p); >> z = f_o_diff( x_to_the_2p_anon, [1,2], .01 ) z = 4.0604 32.2408 >>
Note that for an in-line function the function "name" is in fact the function handle (hence we need no @ in front of the \(\mathrm{x}_{-}\)to_the_2p_anon in the above) - the name and handle for a single-line function coalesce.