TExcelTAD
Home › MATLAB / Octave › Recursion

Recursion

A recursive function solves a problem by calling itself on a smaller version of the same problem. Writing Functions showed the classic factorial; this lesson looks at how recursion actually runs, where it shines (nested data, divide-and-conquer), what it costs, and how to keep it fast and safe.

Every recursive function has two parts:

Part Purpose Factorial example
Base case A version small enough to answer directly; stops the recursion n <= 1 returns 1
Recursive case Reduces the problem and calls itself on the smaller piece n * fact(n - 1)

If the recursive case doesn't move towards a base case, the function calls itself forever, until MATLAB stops it with an error.

Watching the calls

Each call gets its own workspace with its own copy of n. Printing the depth makes the "go down, then come back up" shape visible:

matlab · try it yourself
r = sum_to(4, 0);
fprintf('result: %d\n', r);

function s = sum_to(n, depth)
pad = repmat('  ', 1, depth);
fprintf('%ssum_to(%d) called\n', pad, n);
if n == 0
    s = 0;                         % base case
else
    s = n + sum_to(n - 1, depth + 1);
end
fprintf('%ssum_to(%d) returns %d\n', pad, n, s);
end
sum_to(4) called
  sum_to(3) called
    sum_to(2) called
      sum_to(1) called
        sum_to(0) called
        sum_to(0) returns 0
      sum_to(1) returns 1
    sum_to(2) returns 3
  sum_to(3) returns 6
sum_to(4) returns 10
result: 10

No call can finish until the call it made has finished. The pending calls are kept on the call stack, which is why very deep recursion uses a lot of memory.

Recursion on arrays

Many array problems split naturally into "the first element" and "the rest", or into two halves. Binary search halves the range on every call, so it needs only about log2(n) calls:

matlab · try it yourself
v = [2 5 8 12 16 23 38 56 72 91];
fprintf('23 is at index %d\n', bsearch(v, 23, 1, numel(v)));
fprintf('7 is at index %d\n', bsearch(v, 7, 1, numel(v)));

function idx = bsearch(v, target, lo, hi)
if lo > hi
    idx = 0;                       % base case: empty range, not found
    return
end
mid = floor((lo + hi) / 2);
if v(mid) == target
    idx = mid;
elseif v(mid) < target
    idx = bsearch(v, target, mid + 1, hi);
else
    idx = bsearch(v, target, lo, mid - 1);
end
end
23 is at index 6
7 is at index 0

Divide and conquer: merge sort

Merge sort is the textbook divide-and-conquer algorithm: split the array in half, sort each half recursively, then merge the two sorted halves:

matlab · try it yourself
disp(merge_sort([38 27 43 3 9 82 10]))

function v = merge_sort(v)
if numel(v) <= 1
    return                          % a single element is already sorted
end
mid = floor(numel(v) / 2);
a = merge_sort(v(1:mid));
b = merge_sort(v(mid+1:end));
v = zeros(1, numel(a) + numel(b));  % preallocate the merged result
i = 1; j = 1;
for k = 1:numel(v)
    if j > numel(b) || (i <= numel(a) && a(i) <= b(j))
        v(k) = a(i); i = i + 1;
    else
        v(k) = b(j); j = j + 1;
    end
end
end
    3    9   10   27   38   43   82

In real code you would just call sort, which is much faster, but the pattern (split, solve the parts, combine) appears in many algorithms.

Recursion on nested data

Recursion is the natural tool when data contains data of the same kind, like a cell array whose cells may hold more cell arrays, or a folder that contains folders. The function handles one level and calls itself for anything nested:

matlab · try it yourself
data = {1, {2, 3, {4, {5}}}, 6, {}};
fprintf('sum of all numbers: %d\n', deep_sum(data));
fprintf('nesting depth: %d\n', depth_of(data));

function s = deep_sum(c)
s = 0;
for k = 1:numel(c)
    if iscell(c{k})
        s = s + deep_sum(c{k});    % recurse into the nested cell
    else
        s = s + sum(c{k}(:));
    end
end
end

function d = depth_of(c)
d = 1;
for k = 1:numel(c)
    if iscell(c{k})
        d = max(d, 1 + depth_of(c{k}));
    end
end
end
sum of all numbers: 21
nesting depth: 4

The same shape works for a tree of structs, where each node has a children field:

matlab · try it yourself
leaf = @(name) struct('name', name, 'children', {{}});
tree = struct('name', 'root', 'children', {{ ...
    struct('name', 'src', 'children', {{leaf('main.m'), leaf('util.m')}}), ...
    leaf('README.txt')}});
print_tree(tree, 0);

function print_tree(node, level)
fprintf('%s%s\n', repmat('  ', 1, level), node.name);
for k = 1:numel(node.children)
    print_tree(node.children{k}, level + 1);
end
end
root
  src
    main.m
    util.m
  README.txt

(struct('children', {{...}}) uses double braces so that the whole cell array becomes one field value, rather than creating a struct array.)

Generating combinations

Recursion is also a compact way to enumerate possibilities. Each call fixes one more choice and recurses on the remaining ones:

matlab · try it yourself
P = perms_of('abc');
for k = 1:numel(P)
    fprintf('%s ', P{k});
end
fprintf('\n');

function out = perms_of(s)
if numel(s) <= 1
    out = {s};
    return
end
out = {};
for k = 1:numel(s)
    rest = s([1:k-1, k+1:end]);
    tails = perms_of(rest);
    for t = 1:numel(tails)
        out{end+1} = [s(k) tails{t}];
    end
end
end
abc acb bac bca cab cba

The cost of naive recursion

The direct translation of the Fibonacci definition, fib(n) = fib(n-1) + fib(n-2), recomputes the same values again and again. Counting the calls shows how quickly that explodes:

matlab · try it yourself
for n = [10 15 20]
    [f, calls] = fib_naive(n);
    fprintf('fib(%d) = %d using %d calls\n', n, f, calls);
end

function [f, calls] = fib_naive(n)
if n <= 2
    f = 1;
    calls = 1;
else
    [a, ca] = fib_naive(n - 1);
    [b, cb] = fib_naive(n - 2);
    f = a + b;
    calls = 1 + ca + cb;
end
end
fib(10) = 55 using 109 calls
fib(15) = 610 using 1219 calls
fib(20) = 6765 using 13529 calls

Memoization fixes this: store each result the first time it is computed and look it up afterwards. Here the cache travels in and out of the function as an argument (a persistent variable or a containers.Map would also work):

matlab · try it yourself
memo = zeros(1, 50);
[f, memo] = fib_memo(50, memo);
fprintf('fib(50) = %d\n', f);
fprintf('values cached: %d\n', nnz(memo));

function [f, memo] = fib_memo(n, memo)
if n <= 2
    f = 1;
elseif memo(n) > 0
    f = memo(n);                   % already known: no recursion
else
    [a, memo] = fib_memo(n - 1, memo);
    [b, memo] = fib_memo(n - 2, memo);
    f = a + b;
end
memo(n) = f;
end
fib(50) = 12586269025
values cached: 50

Recursion limits

Both programs refuse to recurse indefinitely. MATLAB stops at 500 levels by default (set(0, 'RecursionLimit', n) changes it); Octave stops at 256 (max_recursion_depth(n)). The error messages differ, so catch the error rather than relying on its text:

matlab · try it yourself
try
    count_down(1000);
catch
    disp('Stopped: the recursion went too deep.')
end
count_down(100);
disp('100 levels are fine.')

function count_down(n)
if n > 0
    count_down(n - 1);
end
end
Stopped: the recursion went too deep.
100 levels are fine.

Raising the limit is rarely the right fix: each level costs memory, and a very deep stack can crash the program. When the recursion is just a disguised loop ("handle one item, recurse on the rest"), write the loop:

matlab · try it yourself
v = 1:1000;
total = 0;
for k = 1:numel(v)         % same result as a recursive "first + sum(rest)"
    total = total + v(k);
end
fprintf('%d %d\n', total, sum(v));
500500 500500

When to use recursion

  • Good fit: nested or tree-shaped data, divide-and-conquer algorithms, generating combinations, problems defined recursively in maths.
  • Poor fit: simple sequences that a loop or a vectorised call (sum, cumsum, prod) handles directly, and anything that needs thousands of levels.
  • Always check that every path reaches a base case, and memoize when the same sub-problem comes up repeatedly.

Learn more: the Data Structures & Algorithms course covers recursion, sorting and searching in depth; Performance & Preallocation explains why merge_sort preallocates its result.

Test yourself

What is the job of the base case in a recursive function?

  1. To make the function faster
  2. To answer the smallest problems directly and stop the recursion
  3. To call the function again
  4. To allocate memory

Why is the naive recursive Fibonacci so slow?

  1. Recursion is always slow in MATLAB
  2. It computes the same smaller Fibonacci numbers many times over
  3. It uses floating-point numbers
  4. It has no base case

What is Octave's default maximum recursion depth?

  1. 64
  2. 256
  3. 500
  4. Unlimited