TExcelTAD
Home › MATLAB / Octave › Performance & Preallocation

Performance & Preallocation

Most MATLAB code is fast enough as soon as it is written clearly. When it isn't, a few habits make the biggest difference: measure first, preallocate arrays, let built-in vectorised functions do the work, and avoid needless copying. Vectorization covered whole-array operations; this lesson is about why some code is slow and how to fix it.

Measure before you optimise

Guessing where time goes is notoriously unreliable. MATLAB and Octave give you three tools:

Tool Use it to…
tic … t = toc Time a block of code (wall-clock seconds)
timeit(@() f(x)) Time a function reliably: runs it several times and returns a typical value (MATLAB; Octave 11 doesn't have it)
profile on … profile viewer See which functions and lines take the time (profshow in Octave)
matlab
n = 1e6;
tic
s = 0;
for k = 1:n
    s = s + sqrt(k);
end
t_loop = toc;

tic
s2 = sum(sqrt(1:n));
t_vec = toc;
fprintf('loop: %.4f s   vectorised: %.4f s\n', t_loop, t_vec);
text
loop: 0.0124 s   vectorised: 0.0031 s        (sample timing, MATLAB R2025b on a laptop)

Timings vary from run to run and machine to machine, and MATLAB's just-in-time compiler makes simple loops far faster than they used to be, while Octave's interpreter runs loops much more slowly (often 10 to 100 times slower than the vectorised form). So the examples below don't print timings: they count the work, which is what timings ultimately reflect.

Why growing an array is slow

An array is stored in one contiguous block of memory. When you assign past its end, MATLAB has to allocate a bigger block and copy every existing element into it. In a loop that adds one element per step, step k copies k - 1 elements, so the total work grows with the square of n:

matlab · try it yourself
for n = [100 1000 10000]
    copies = sum(0:n-1);        % elements copied when growing one by one
    fprintf('n = %5d: about %10d element copies when growing, 0 when preallocated\n', n, copies);
end
n =   100: about       4950 element copies when growing, 0 when preallocated
n =  1000: about     499500 element copies when growing, 0 when preallocated
n = 10000: about   49995000 element copies when growing, 0 when preallocated

(Modern MATLAB is sometimes clever enough to over-allocate behind the scenes, but you can't rely on it, and Octave doesn't do it.)

Preallocating means creating the array at its final size first, then filling it in. The result is identical:

matlab · try it yourself
n = 8;
grown = [];
for k = 1:n
    grown(end + 1) = k^2;       % grows: reallocates every time
end

pre = zeros(1, n);              % allocate once
for k = 1:n
    pre(k) = k^2;               % fills in place
end
disp(pre)
fprintf('identical: %d\n', isequal(grown, pre));
    1    4    9   16   25   36   49   64
identical: 1

The editor's code analyser even underlines grown(end + 1) = ... inside a loop with a warning suggesting preallocation.

Preallocating every kind of container

Container Preallocate with
Numeric array zeros(r, c), ones(r, c), nan(r, c)
Integer / single zeros(r, c, 'int32'), zeros(r, c, 'single')
Logical array false(r, c), true(r, c)
Cell array cell(r, c)
Struct array struct('field', cell(1, n)) or repmat(template, 1, n)
Same type and size as A zeros(size(A), 'like', A)
matlab · try it yourself
n = 4;
names = cell(1, n);
people = struct('name', cell(1, n), 'age', cell(1, n));
for k = 1:n
    names{k} = sprintf('user%d', k);
    people(k).name = names{k};
    people(k).age = 20 + 3 * k;
end
fprintf('%s ', names{:});
fprintf('\n');
fprintf('%d people, last one is %s aged %d\n', numel(people), people(end).name, people(end).age);
flags = false(1, n);
flags([2 4]) = true;
disp(flags)
user1 user2 user3 user4
4 people, last one is user4 aged 32
  0  1  0  1

When the final size is unknown

If you don't know how many results you'll get, preallocate an upper bound and trim at the end, or grow the capacity in big steps (doubling) rather than one element at a time:

matlab · try it yourself
% Collect the numbers below 200 whose digits sum to 10
found = zeros(1, 200);          % upper bound: at most 200 results
count = 0;
for x = 1:199
    if sum(num2str(x) - '0') == 10
        count = count + 1;
        found(count) = x;
    end
end
found = found(1:count);         % trim the unused part
fprintf('%d numbers: %s\n', count, mat2str(found));

% Doubling: how many reallocations to reach 10000 elements?
capacity = 16;
reallocs = 0;
for needed = 1:10000
    if needed > capacity
        capacity = 2 * capacity;
        reallocs = reallocs + 1;
    end
end
fprintf('doubling: %d reallocations instead of 10000\n', reallocs);
19 numbers: [19 28 37 46 55 64 73 82 91 109 118 127 136 145 154 163 172 181 190]
doubling: 10 reallocations instead of 10000

Let built-in functions do the work

Built-in functions run in compiled code and process whole arrays at once. A loop that does what a built-in does is almost always slower, and longer. A few that replace common loops:

Instead of a loop that… Use
sums, counts or averages groups accumarray(groups, values)
checks membership in a list ismember(a, list)
computes running totals / maxima cumsum, cummax
finds the first match find(cond, 1)
compares every pair of elements implicit expansion: a - b'
matlab · try it yourself
% Total sales per store: store numbers and amounts
store  = [2 1 3 2 1 2 3];
amount = [10 25 5 40 15 20 30];

% Loop version
totals_loop = zeros(1, 3);
for k = 1:numel(store)
    totals_loop(store(k)) = totals_loop(store(k)) + amount(k);
end

% Built-in version: one call
totals = accumarray(store', amount')';
disp(totals)
fprintf('same result: %d\n', isequal(totals, totals_loop));

% Membership without a nested loop
banned = [3 7 9];
codes = [1 3 5 7 8];
disp(ismember(codes, banned))
   40   70   35
same result: 1
  0  1  0  1  0

Work with the memory layout

MATLAB stores matrices column by column ("column-major"): A(1,1), A(2,1), A(3,1), then the second column. Code that walks down columns touches memory in order, which is friendlier to the processor's cache. For nested loops over a large matrix, put the row index in the inner loop:

matlab · try it yourself
A = reshape(1:6, 2, 3)
disp(A(:)')                  % the order in memory
total = 0;
for c = 1:size(A, 2)         % outer: columns
    for r = 1:size(A, 1)     % inner: rows (adjacent in memory)
        total = total + A(r, c);
    end
end
fprintf('total: %d\n', total);
A =

   1   3   5
   2   4   6

   1   2   3   4   5   6
total: 21

Avoid repeated and hidden work

  • Move invariant work out of loops. A value that doesn't change inside the loop should be computed once before it.
  • Copies happen on write. B = A doesn't copy anything until you modify B, and passing a large array to a function is free as long as the function only reads it. Modifying an input inside a function does create a copy.
  • Choose a smaller type when memory is the problem:
matlab · try it yourself
arrays = {zeros(1000, 1), zeros(1000, 1, 'single'), zeros(1000, 1, 'int16'), ...
          zeros(1000, 1, 'uint8'), false(1000, 1)};
for k = 1:numel(arrays)
    v = arrays{k};
    info = whos('v');
    fprintf('%-8s %5d bytes for 1000 elements\n', class(v), info.bytes);
end
double    8000 bytes for 1000 elements
single    4000 bytes for 1000 elements
int16     2000 bytes for 1000 elements
uint8     1000 bytes for 1000 elements
logical   1000 bytes for 1000 elements

For matrices that are mostly zeros, Sparse Matrices store only the non-zero entries.

A checklist

  1. Make it correct and clear first; then measure with tic/toc or the profiler.
  2. Preallocate every array that a loop fills.
  3. Replace element-by-element loops with built-ins and vectorised expressions where it keeps the code readable.
  4. Move repeated work out of loops; loop down columns.
  5. Stop when it's fast enough. A two-line loop that runs in a millisecond doesn't need tuning.

Learn more: arrayfun & cellfun (convenient, but usually not faster than a loop), Sparse Matrices, and the same ideas for Python in NumPy.

Test yourself

Why is v(end+1) = x inside a long loop slow?

  1. end is a slow keyword
  2. Each time the array grows, MATLAB may allocate a new block and copy all existing elements
  3. It converts the array to a cell array
  4. It isn't slow

How do you preallocate a 1-by-50 cell array?

  1. zeros(1, 50)
  2. cell(1, 50)
  3. {}(50)
  4. struct(1, 50)

In nested loops over a large matrix A(r, c), which index should the inner loop vary?

  1. The column index c
  2. The row index r
  3. It makes no difference
  4. Neither; use while loops