TExcelTAD
Home › MATLAB / Octave › Local & Nested Functions

Local & Nested Functions

As soon as a program grows beyond a few dozen lines, you split it into functions. MATLAB gives you several places to put them, and each one has a different visibility (who can call it) and a different relationship to the variables around it:

Kind Where it lives Who can call it Shares variables?
Main (primary) function First function in name.m Anyone, if the file is on the path No
Local function After the main function or after script code, in the same file Only code in that file No
Nested function Inside another function, before its end The parent, its other nested functions, or through a handle Yes, with the parent
Private function A file in a private/ subfolder Only files in the folder just above No

You met local functions in Scripts vs Functions and the basics of workspaces in Variable Scope. This lesson goes further: how local functions organise a file, how MATLAB decides which function a name refers to, and what nested functions can do that nothing else can.

Local functions in a script

Since R2016b a script can end with any number of local functions. They can call each other, in any order, and only this file can see them:

matlab · try it yourself
scores = [72 88 95 61 79];
report('Group A', scores);
report('Group B', [55 67 70]);

function report(label, v)
fprintf('%-8s %s\n', label, summary_line(v));
end

function s = summary_line(v)
s = sprintf('n=%d  mean=%.1f  range=%s', numel(v), mean(v), range_text(v));
end

function t = range_text(v)
t = sprintf('%g..%g', min(v), max(v));
end
Group A  n=5  mean=79.0  range=61..95
Group B  n=3  mean=64.0  range=55..70

Each local function has its own workspace: summary_line cannot see scores, it only sees its input v. Remember that MATLAB requires the local functions to come after all of the script code.

Local functions in a function file

A function file starts with its main function; every function after it is a local function (MATLAB used to call them "subfunctions"). Below, the script calls grade_report, which lives in its own file together with two helpers. (In this course, a line % --- file: grade_report.m starts a separate file next to the script.)

matlab · try it yourself
grade_report([45 72 88 91 59]);
fprintf('Can the script see letter_grade? exist = %d\n', exist('letter_grade'));

% --- file: grade_report.m
function grade_report(marks)
% GRADE_REPORT  Print a letter grade for every mark.
for m = marks
    fprintf('%3d -> %s\n', m, letter_grade(m));
end
fprintf('Pass rate: %s\n', pct(mean(marks >= 50)));
end

function g = letter_grade(m)
edges = [0 50 65 80];
letters = 'FCBA';
g = letters(find(m >= edges, 1, 'last'));
end

function s = pct(fraction)
s = sprintf('%.0f%%', 100 * fraction);
end
 45 -> F
 72 -> B
 88 -> A
 91 -> A
 59 -> C
Pass rate: 80%
Can the script see letter_grade? exist = 0

exist returns 0 because letter_grade is not on the path: only code inside grade_report.m can call it. That is exactly what you want for helpers that are implementation details. If several files need the same helper, move it to its own function file instead.

Which function does a name mean?

When MATLAB sees a call like scale(x), it looks for the name in a fixed order. The most important rules, from highest to lowest priority:

  1. A variable with that name in the current workspace.
  2. A nested function of the current function.
  3. A local function in the current file.
  4. A private function (in private/ next to the current file).
  5. Class constructors and methods, then functions in the current folder, then the rest of the path, including built-ins.

So a local function quietly wins over a file of the same name, but only inside its own file. Here a function file scale.m doubles its input, while scaled_report.m has its own local scale that triples it:

matlab · try it yourself
disp(scale(10))            % the script sees scale.m
scaled_report(10);         % inside scaled_report.m, the local scale wins

% --- file: scale.m
function y = scale(x)
y = 2 * x;
end

% --- file: scaled_report.m
function scaled_report(x)
fprintf('scaled: %g\n', scale(x));
end

function y = scale(x)
y = 3 * x;
end
20
scaled: 30

The same rule means a local function called max or sum would hide the built-in for the whole file. That is legal but confusing, so give helpers distinctive names. which name tells you which definition a name currently resolves to.

Nested functions

A nested function is written inside its parent, before the parent's end. Unlike a local function, it shares variables with the parent: any variable that the parent also uses is the same variable in both. Nested functions only work in function files (and class files), never in scripts, and every function in such a file must be closed with end.

matlab · try it yourself
[n, total] = tally([3 8 -2 5 -7 4]);
fprintf('%d positive values, total %g\n', n, total);

% --- file: tally.m
function [count, total] = tally(values)
count = 0;
total = 0;
for v = values
    if v > 0
        add(v);
    end
end

    function add(x)
        % 'count' and 'total' belong to the parent: no inputs or outputs needed
        count = count + 1;
        total = total + x;
    end
end
4 positive values, total 20

The rules for sharing:

  • A variable is shared when it appears in the parent's code (anywhere, even after the nested function is called).
  • A variable that appears only inside the nested function is private to it and disappears when it returns.
  • A nested function's inputs and outputs are always its own, even if the parent has variables with the same names.

Nested functions keep state

The most useful trick is returning a handle to a nested function. The handle keeps the parent's workspace alive, so the shared variables survive between calls. This is how you build a small object with private state, without writing a class:

matlab · try it yourself
acc = make_account(100);
acc.deposit(50);
acc.withdraw(30);
fprintf('Balance: %g\n', acc.balance());

other = make_account(5);       % a second, independent account
other.deposit(1);
fprintf('Other: %g, first still %g\n', other.balance(), acc.balance());

% --- file: make_account.m
function acc = make_account(start)
balance = start;               % shared by all three nested functions
acc.deposit = @deposit;
acc.withdraw = @withdraw;
acc.balance = @get_balance;

    function deposit(amount)
        balance = balance + amount;
    end

    function withdraw(amount)
        balance = balance - amount;
    end

    function b = get_balance()
        b = balance;
    end
end
Balance: 120
Other: 6, first still 120

Each call to make_account creates a fresh workspace, so the two accounts don't interfere. Compare this with an anonymous function, which only copies the variables it captures (see Anonymous Functions & Handles): a nested function can change them. For anything bigger than a few operations, a handle class is usually clearer.

A few restrictions come with nested functions in MATLAB: you can't create variables dynamically in a function that contains nested functions (no eval('x = 1'), assignin or loading a MAT-file without an output), and a script can't contain them at all.

Private functions

A folder called private makes its functions visible only to the files in the folder directly above it. It's a way to share helpers between several files of a project without putting them on the path for everyone:

text
my_toolbox/
  analyse.m            % can call clean_up and parse_header
  plot_summary.m       % can call them too
  private/
    clean_up.m
    parse_header.m

You never add private to the path yourself; MATLAB and Octave handle it automatically.

Choosing

  • One script with a few helpers: local functions at the end of the script.
  • A reusable function with internal helpers: a function file with local functions.
  • Helpers shared by a few files of one project: a private/ folder.
  • A function that must remember or change state between calls: a nested function handle, a persistent variable, or a class.

Learn more: Writing Functions, Variable Scope and, for state with methods, Classes (classdef).

Test yourself

Who can call a local function defined in report.m after the main function?

  1. Any code on the path
  2. Only code inside report.m
  3. Only scripts
  4. Only functions in a private/ folder

A function file defines a local function scale, and the path also contains scale.m. What does scale(1) inside that file call?

  1. scale.m
  2. The local function
  3. It is an error
  4. Whichever was created last

What can a nested function do that a local function cannot?

  1. Return several outputs
  2. Read and change its parent's variables directly
  3. Be called from other files by name
  4. Run inside a script