Preallocation
for and while loops that incrementally increase the size of a data structure each time
through the loop can adversely affect performance and memory use. Repeatedly resizing
arrays often requires MATLAB to spend extra time looking for larger contiguous blocks of
memory, and then moving the array into those blocks. Often, you can improve code
execution time by preallocating the maximum amount of space required for the array.
The following code displays the amount of time needed to create a scalar variable, x, and
then to gradually increase the size of x in a for loop.
tic
x = 0;
for k = 2:1000000
x(k) = x(k-1) + 5;
end
toc
Elapsed time is 0.301528 seconds.
If you preallocate a 1-by-1,000,000 block of memory for x and initialize it to zero, then the
code runs much faster because there is no need to repeatedly reallocate memory for the
growing data structure.
tic
x = zeros(1, 1000000);
for k = 2:1000000
x(k) = x(k-1) + 5;
end
toc
Elapsed time is 0.011938 seconds.
Use the appropriate preallocation function for the kind of array you want to initialize:
- zeros for numeric arrays
- cell for character arrays
Preallocating a Nondouble Matrix
When you preallocate a block of memory to hold a matrix of some type other than
double, avoid using the method
Preallocation