Programming and Data Types | ![]() ![]() |
You can often improve code execution time by preallocating the arrays that store output results. 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 array |
|
y = zeros(1,100);
|
Cell array |
|
B = cell(2,3); B{1,3} = 1:3; B{2,2} = 'string'; |
Structure array |
|
|
Preallocation also helps reduce memory fragmentation if you work with large matrices. In the course of a MATLAB session, memory can become fragmented due to dynamic memory allocation and deallocation. This can result in plenty of free memory, but not enough contiguous space to hold a large variable. Preallocation helps prevent this by allowing MATLAB to "grab" sufficient space for large data constructs at the beginning of a computation.
Preallocating a Nondouble Matrix
When you preallocate a block of memory to hold a matrix of some type other than double
, it is more memory efficient and sometimes faster to use the repmat
function for this.
The statement below uses zeros
to preallocate a 100-by-100 matrix of uint8
. It does this by first creating a full matrix of double
s, and then converting the matrix to uint8
. This costs time and uses memory unnecessarily.
Using repmat
, you create only one double
, thus reducing your memory needs.
Use repmat When You Need to Enlarge Arrays
In cases where you cannot preallocate, see if you can increase the size of your array using the repmat
function. repmat
tries to get you a contiguous block of memory for your expanding array.
![]() | Vectorizing Loops | Other Ways to Speed Up Performance | ![]() |