Programming Previous page   Next Page

Preallocating Arrays

for and while loops that incrementally increase, or grow, the size of a data structure each time through the loop can adversely affect performance and memory use. Repeatedly resizing arrays often requires that MATLAB spend extra time looking for larger contiguous blocks of memory and then moving the array into those blocks. You can often improve on code execution time by preallocating the maximum amount of space that would be required for the array ahead of time.

The following code creates a scalar variable x, and then gradually increases the size of x in a for loop instead of preallocating the required amount of memory at the start:

Change the first line to preallocate a 1-by-1000 block of memory for x initialized to zero. This time there is no need to repeatedly reallocate memory and move data as more values are assigned to x in the loop:

Preallocation Functions

Preallocation makes it unnecessary for MATLAB to resize an array each time you enlarge it. Use the appropriate preallocation function for the kind of array you are working with.

Array Type
Function
Examples
Numeric
zeros
y = zeros(1, 100);

Cell
cell
B = cell(2, 3);
B{1,3} = 1:3;
B{2,2} = 'string';

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

This statement preallocates a 100-by-100 matrix of int8 first by creating a full matrix of doubles, and then converting each element to int8. This costs time and uses memory unnecessarily.

The next statement shows how to do this more efficiently:


Previous page  Techniques for Improving Performance Coding Loops in a MEX-File Next page

© 1994-2005 The MathWorks, Inc.