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
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
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
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
When you preallocate a block of memory to hold a matrix of some
type other than
double, avoid using the method
A = int8(zeros(100));
This statement preallocates a 100-by-100 matrix of
first by creating a full matrix of
and then by converts each element to
the array as
int8 values saves time and memory.
A = zeros(100, 'int8');