11.12.2 Anonymous Functions

Anonymous functions are defined using the syntax

@(argument-list) expression

Any variables that are not found in the argument list are inherited from the enclosing scope. Anonymous functions are useful for creating simple unnamed functions from expressions or for wrapping calls to other functions to adapt them for use by functions like quad. For example,

f = @(x) x.^2;
quad (f, 0, 10)
    ⇒ 333.33

creates a simple unnamed function from the expression x.^2 and passes it to quad,

quad (@(x) sin (x), 0, pi)
    ⇒ 2

wraps another function, and

a = 1;
b = 2;
quad (@(x) betainc (x, a, b), 0, 0.4)
    ⇒ 0.13867

adapts a function with several parameters to the form required by quad. In this example, the values of a and b that are passed to betainc are inherited from the current environment.

Note that for performance reasons it is better to use handles to existing Octave functions, rather than to define anonymous functions which wrap an existing function. The integration of sin (x) is 5X faster if the code is written as

quad (@sin, 0, pi)

rather than using the anonymous function @(x) sin (x). There are many operators which have functional equivalents that may be better choices than an anonymous function. Instead of writing

f = @(x, y) x + y

this should be coded as

f = @plus

See Operator Overloading, for a list of operators which also have a functional form.

© 1996–2020 John W. Eaton
Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies.
Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one.
Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions.
https://octave.org/doc/v6.3.0/Anonymous-Functions.html