23.06.2015 Views

MATLAB Programming

MATLAB Programming

MATLAB Programming

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Using Memory Efficiently<br />

• Allocate your larger matrices first, as explained in “Allocating Large<br />

Matrices Earlier” on page 11-19.<br />

• Set variables equal to the empty matrix [] to free memory, or clear the<br />

variables using the clear function.<br />

• Reuse variables as much as possible, but keeping in mind the guidelines<br />

stated in “Assigning to Variables” on page 11-9.<br />

Preallocating Arrays to Reduce Fragmentation<br />

In the course of a <strong>MATLAB</strong> session, memory can become fragmented due<br />

to dynamic memory allocation and deallocation. for and while loops that<br />

incrementally increase, or grow, the size of a data structure each time through<br />

the loop can add to this fragmentation as they have to repeatedly find and<br />

allocate larger blocks of memory to store the data.<br />

To make more efficient use of your memory, preallocate a block of memory<br />

large enough to hold the matrix at its final size before entering the loop.<br />

When you preallocate memory for a potentially large array, <strong>MATLAB</strong> “grabs”<br />

sufficient contiguous space for the data at the beginning of the computation.<br />

Once you have this space, you can add elements to the array without having<br />

to continually allocate new space for it in memory.<br />

For more information on preallocation, see “Preallocating Arrays” on page<br />

11-7.<br />

Allocating Large Matrices Earlier<br />

<strong>MATLAB</strong> uses a heap method of memory management. It requests memory<br />

from the operating system when there is not enough memory available in the<br />

<strong>MATLAB</strong> heap to store the current variables. It reuses memory as long as the<br />

size of the memory segment required is available in the <strong>MATLAB</strong> heap.<br />

For example, on one machine these statements use approximately 15.4 MB<br />

of RAM:<br />

a = rand(1e6,1);<br />

b = rand(1e6,1);<br />

This statement uses approximately 16.4 MB of RAM:<br />

11-19

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!