Writing Fast Matlab Code #3: Preallocation
Array Preallocation
Matlab’s matrix variables have the ability to dynamically augment rows and columns. For example,
>> a = 2
a =
2
>> a(2,6) = 1
a = |
||||||
2 |
0 |
0 |
0 |
0 |
0 |
|
0 |
0 |
0 |
0 |
0 |
1 |
|
Matlab automatically resizes the matrix. Internally, the matrix data memory must be reallocated with larger size. If a matrix is resized repeatedly—like within a loop—this overhead can be significant. To avoid frequent reallocations, preallocate the matrix with the zeros command.
Consider the code:
a(1) = 1; b(1) = 0; for k = 2:8000 a(k) = 0.99803 * a(k − 1) − 0.06279 * b(k − 1); b(k) = 0.06279 * a(k − 1) + 0.99803 * b(k − 1); end
This code takes 0.47 seconds to run. After the for loop, both arrays are row vectors of length 8000,
thus to preallocate, create empty a and b row vectors each with 8000 elements.
a = zeros(1,8000); % Preallocation b = zeros(1,8000); a(1) = 1; b(1) = 0; for k = 2:8000 a(k) = 0.99803 * a(k − 1) − 0.06279 * b(k − 1); b(k) = 0.06279 * a(k − 1) + 0.99803 * b(k − 1); end
With this modification, the code takes only 0.14 seconds (over three times faster). Preallocation is often easy to do, in this case it was only necessary to determine the right preallocation size and add two lines.
What if the final array size can vary? Here is an example:
a = zeros(1,10000); % Preallocate count = 0; for k = 1:10000 v = exp(rand*rand); if v > 0.5 % Conditionally add to array count = count + 1; a(count) = v; end end a = a(1:count); % Trim extra zeros from the results
The average run time of this program is 0.42 seconds without preallocation and 0.18 seconds with it.
Preallocation is also beneficial for cell arrays, using the cell command to create a cell array of the desired size.
Popularity: 1% [?]


















































