Anonymous Functions (GNU Octave (version 8.2.0))

Previous: Function Handles, Up: Function Handles and Anonymous Functions [Contents][Index]

#### 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.

Previous: Function Handles, Up: Function Handles and Anonymous Functions [Contents][Index]