If you remove elements from an existing array, MATLAB keeps the memory storage
contiguous by removing the deleted elements, and then compacting its storage in the
original memory location.
Working with Large Data Sets
If you are working with large data sets, you need to be careful when increasing the size of
an array to avoid getting errors caused by insufficient memory. If you expand the array
beyond the available contiguous memory of its original location, MATLAB must make a
copy of the array and set this copy to the new value. During this operation, there are two
copies of the original array in memory. This temporarily doubles the amount of memory
required for the array and increases the risk of your program running out of memory
during execution. It is better to preallocate sufficient memory for the largest potential
size of the array at the start. See “Preallocation” on page 28-17.
Copying Arrays
Internally, multiple variables can point to the same block of data, thus sharing that array's
value. When you copy a variable to another variable (e.g., B = A), MATLAB makes a copy
of the array reference, but not the array itself. As long as you do not modify the contents
of the array, there is no need to store more than one copy of it. If you do modify any
elements of the array, MATLAB makes a copy of the array and then modifies that copy.
This example uses the memory function to demonstrate how MATLAB handles copying
arrays. memory is available only on Windows systems.
Start by creating a simple script memUsed.m to display how much memory is being used
by your MATLAB process. Put these two lines of code in the script.
[usr, sys] = memory;
usr.MemUsedMATLAB
Get an initial reading of how much memory is being used by your MATLAB process:
format short eng;
memUsed
ans =
295.4977e+006
Create a 2000-by-2000 numeric array A. This uses about 32MB of memory:
A = magic(2000);
memUsed
How MATLAB Allocates Memory