Programming and Data Types |
 |
Preallocating Arrays
You can often improve code execution time by preallocating the arrays that store output results. Preallocation prevents MATLAB from having 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
|
zeros
|
y = zeros(1,100);
|
Cell array
|
cell
|
B = cell(2,3);
B{1,3} = 1:3;
B{2,2} = 'string';
|
Structure array
|
struct , repmat
|
data = repmat(struct('x',[1 3],...
'y',[5 6]), 1, 3);
|
|
|
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.
| Optimizing MATLAB Code | | Making Efficient Use of Memory |  |