Skip to content
Functions
step 1/5

Reading — step 1 of 5

Learn

~1 min readControl Flow and Functions

Functions are defined with function:

function y = square(x)
    y = x .^ 2;
endfunction

square(5)        % 25

The assigned variable is the return value (in this case y). Multi-return:

function [minimum, maximum] = bounds(v)
    minimum = min(v);
    maximum = max(v);
endfunction

[lo, hi] = bounds([3, 1, 4, 1, 5]);   % lo=1, hi=5

Anonymous functions with @:

square = @(x) x .^ 2;
add = @(a, b) a + b;

square(5)        % 25
add(3, 4)        % 7

Higher-order built-ins:

arrayfun(@(x) x * 2, [1, 2, 3])     % [2 4 6]
cellfun(@length, {"hi", "hello"})   % [2 5]

Discussion

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

Sign in to post a comment or reply.

Loading…