Technical Solutions
How do I pre-allocate memory when using MATLAB?
Date Last Modified: Friday, June 26, 2009
| Solution ID: | 1-18150 | |
| Product: | MATLAB | |
| Reported in Release: | No Release | |
| Platform: | All Platforms | |
| Operating System: | All OS |
Subject:
How do I pre-allocate memory when using MATLAB?
Problem Description:
I have several FOR loops in my M-file. I have tried using the PACK function, but I continue to get "out of memory" errors.
Solution:If the matrix size is not defined prior to populating it with data through a FOR loop, memory fragmentation problems may happen since MATLAB is not aware of the final matrix size upon the conclusion of the FOR loop. For example, look at the following FOR loop:
On the other hand, pre-allocating the memory ahead of time
tic;
returns:For pre-allocating memory for a cell array, you may use the following command:
c = cell(m, n, p,...)
It creates an m-by-n-by-p-... cell array of empty matrices. Arguments m, n, p,... must be scalars.It should be noted that preallocating memory does not make sense if you do not know the eventual size of the matrix you wish to create. This is because one of two cases are likely to occur. Either the preallocated memory will either be too large, resulting in wasted memory; or the allotted memory will be too small for the matrix you are trying to create, resulting in the need to allocate more memory and copy matrix elements to the new space. The latter case will cause you to be just as vulnerable to the memory fragmentation problems you are trying to avoid by preallocating memory. |
Related Solutions:
|
|
Store

