MATLAB Programming Fundamentals - MathWorks

(やまだぃちぅ) #1

How to Avoid Fragmenting Memory


MATLAB always uses a contiguous segment of memory to store a numeric array. As you
manipulate this data, however, the contiguous block can become fragmented. When
memory is fragmented, there might be plenty of free space, but not enough contiguous
memory to store a new large variable. Increasing fragmentation can use significantly
more memory than is necessary.


Preallocate Contiguous Memory When Creating Arrays


In the course of a MATLAB session, memory can become fragmented due to dynamic
memory allocation and deallocation. for and while loops that incrementally increase, or
grow, the size of a data structure each time through the loop can add to this
fragmentation as they have to repeatedly find and allocate larger blocks of memory to
store the data.


To make more efficient use of your memory, preallocate a block of memory large enough
to hold the matrix at its final size before entering the loop. When you preallocate memory
for an array, MATLAB reserves sufficient contiguous space for the entire full-size array at
the beginning of the computation. Once you have this space, you can add elements to the
array without having to continually allocate new space for it in memory.


For more information on preallocation, see “Preallocation” on page 28-17.


Allocate Your Larger Arrays First


MATLAB uses a heap method of memory management. It requests memory from the
operating system when there is not enough memory available in the heap to store the
current variables. It reuses memory as long as the size of the memory segment required
is available in the heap.


The following statements can require approximately 4.3 MB of RAM. This is because
MATLAB might not be able to reuse the space previously occupied by two 1 MB arrays
when allocating space for a 2.3 MB array:


a = rand(1e6,1);
b = rand(1e6,1);
clear
c = rand(2.3e6,1);


The simplest way to prevent overallocation of memory is to allocate the largest vectors
first. These statements require only about 2.0 MB of RAM:


Strategies for Efficient Use of Memory
Free download pdf