This is machine translation

Translated by Microsoft
Mouseover text to see original. Click the button below to return to the English version of the page.

Note: This page has been translated by MathWorks. Click here to see
To view all translated materials including this page, select Country from the country navigator on the bottom of this page.


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.

x = 0;
for k = 2:1000000
   x(k) = x(k-1) + 5;
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.

x = zeros(1, 1000000);
for k = 2:1000000
   x(k) = x(k-1) + 5;
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

A = int8(zeros(100));

This statement preallocates a 100-by-100 matrix of int8, first by creating a full matrix of double values, and then by converts each element to int8. Creating the array as int8 values saves time and memory. For example:

A = zeros(100, 'int8');

Related Examples

More About

Was this topic helpful?