Skip to content
Anonymous Functions and Function Handles
step 1/5

Reading — step 1 of 5

Learn

~1 min readHeterogeneous Data

Octave has first-class functions via handles — created with @.

Reference an existing function:

f = @sin;
f(0)               % 0
f(pi)              % near 0

Anonymous functions:

square = @(x) x^2;
square(5)          % 25

add = @(a, b) a + b;
add(3, 4)          % 7

Closures — anonymous functions capture surrounding variables:

base = 10;
add_base = @(x) x + base;
add_base(5)        % 15

base = 100;        % doesn't affect add_base — base was captured at definition
add_base(5)        % still 15

Higher-order use:

arrayfun(@(n) n^2, 1:5)             % [1 4 9 16 25]
cellfun(@toupper, {"hi", "there"}, "UniformOutput", false)
                                     % {"HI", "THERE"}

UniformOutput=false returns a cell array (since strings have varying lengths). Default true requires uniform output (numeric).

feval — call a handle by name:

feval(@square, 5)         % 25
feval("square", 5)        % also works with string

func2str / str2func — convert between function handle and string:

func2str(@sin)            % "@sin"
str2func("sin")(0)        % 0

Useful for dispatch tables, dynamic configurations.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…