Basti's Scratchpad on the Internet
10 Apr 2018

Appending to Matlab Arrays

The variable $var appears to change size on every loop iteration. Consider preallocating for speed.

So sayeth Matlab.

Let's try it:

x_prealloc = cell(10000, 1);
x_end = {};
x_append = {};
for n=1:10000
    % variant 1: preallocate
    x_prealloc(n) = {42};
    % variant 2: end+1
    x_end(end+1) = {42};
    % variant 3: append
    x_append = [x_append {42}];

Which variant do you think is fastest?


Unsurprisingly, preallocation is indeed faster than growing an array. What is surprising is that it is faster by a constant factor of about 2 instead of scaling with the array length. Only appending by x = [x {42}] actually becomes slower for larger arrays. (The same thing happens for numerical arrays, struct arrays, and object arrays.)

TL;DR: Do not use x = [x $something], ever. Instead, use x(end+1) = $something. Preallocation is generally overrated.

Tags: matlab
Other posts
Creative Commons License by Bastian Bechtold is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.