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 />

and stores the array data in that block. It also stores information about the<br />

array data, such as its data type and dimensions, in a separate, small block of<br />

memory called a header. The variable that you assign this data to is actually<br />

a pointer to the data; it does not contain the data.<br />

If you add new elements to an existing array, <strong>MATLAB</strong> expands the existing<br />

array in memory in a way that keeps its storage contiguous. This might<br />

require finding a new block of memory large enough to hold the expanded<br />

array, and then copying the contents of the array from its original location to<br />

the new block in memory, adding the new elements to the array in this block,<br />

and freeing up the original array location in memory.<br />

If you remove elements from an existing array, <strong>MATLAB</strong> keeps the memory<br />

storage contiguous by removing the deleted elements, and then compacting its<br />

storage in the original memory location.<br />

Working with Large Data Sets. If you are working with large data sets,<br />

you need to be careful when increasing the size of an array to avoid getting<br />

errors caused by insufficient memory. If you expand the array beyond the<br />

available contiguous memory of its original location, <strong>MATLAB</strong> has to make<br />

a copy of the array in a new location in memory, as explained above, and<br />

then set this array to its new value. During this operation, there are two<br />

copies of the original array in memory, thus temporarily doubling the amount<br />

of memory required for the array and increasing the risk of your program<br />

running out of memory during execution. It is better to preallocate sufficient<br />

memory for the array at the start. See “Preallocating Arrays” on page 11-7.<br />

Copying Arrays<br />

Internally, multiple variables can point to the same block of data, thus<br />

sharing that array’s value. When you copy a variable to another variable (e.g.,<br />

B = A), <strong>MATLAB</strong> makes a copy of the pointer, not the array. For example,<br />

thefollowingcodecreatesasingle500-by-500matrixandtwopointerstoit,<br />

A and B:<br />

A = magic(500);<br />

B = A;<br />

11-13

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

Saved successfully!

Ooh no, something went wrong!