Skip to content
Defining Functions in Files
step 1/5

Reading — step 1 of 5

Learn

~1 min readLinear Algebra and I/O

Octave has two ways to define functions:

Function handle / anonymous — for one-liners (covered earlier).

Function file — for multi-line. Filename must match the function name (square.m):

% File: square.m
function y = square(x)
    y = x .^ 2;
endfunction

Multiple returns:

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

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

Local functions — defined in the same .m file, accessible only within that file:

function main_func()
    x = helper(5);
    printf("%d\n", x);
endfunction

function y = helper(x)
    y = x * 2;
endfunction

The first function in a file is the "main" function — its name should match the file. Subsequent functions are local.

Default arguments via nargin:

function y = greet(name, greeting)
    if nargin < 2
        greeting = "Hello";
    end
    y = [greeting ", " name];
endfunction

nargin is the number of arguments actually passed. nargout is similar for return values.

Variable arguments with varargin:

function y = sum_all(varargin)
    y = 0;
    for i = 1:length(varargin)
        y = y + varargin{i};
    end
endfunction

For judge0 (single-file submission), define functions in the same script — they'll be available throughout the run.

Discussion

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

Sign in to post a comment or reply.

Loading…