Programming |
Data Structures and Memory
Memory requirements differ for the various types of MATLAB data structures. You may be able to reduce the amount of memory used for these structures by considering how MATLAB stores them.
Numeric Arrays
MATLAB requires 1, 2, 4, or 8 bytes to store 8-bit, 16-bit, 32-bit, and 64-bit signed and unsigned integers respectively. For floating-point numbers, MATLAB uses 4 or 8 bytes for single
and double
types. To conserve memory, The MathWorks recommends that you use the smallest integer or floating-point type that will contain your data without overflowing. For more information, see Numeric Types in the MATLAB Programming section on Data Types.
Complex Arrays
MATLAB stores complex data as separate real and imaginary parts. If you make a copy of a complex array variable, and then modify only the real or imaginary part of the array, MATLAB creates a new array containing both real and imaginary parts.
Sparse Matrices
It is best to store matrices with values that are mostly zero in sparse format. Sparse matrices can use less memory and may also be faster to manipulate than full matrices. You can convert a full matrix to sparse format using the sparse
function.
Compare two 1000-by-1000 matrices: X
, a matrix of doubles with 2/3 of its elements equal to zero; and Y
, a sparse copy of X
. As shown below, approximately half as much memory is required for the sparse matrix:
whos Name Size Bytes Class X 1000x1000 8000000 double array Y 1000x1000 4004000 double array (sparse)
The following functions can help you to manage memory use in MATLAB:
whos
shows how much memory has been allocated for variables in the workspace.
pack
saves existing variables to disk, and then reloads them contiguously. This reduces the chances of running into problems due to memory fragmentation.
clear
removes variables from memory. One way to increase the amount of available memory is to periodically clear variables from memory that you no longer need.
If you use pack
and there is still not enough free memory to proceed, you probably need to remove some of the variables you are no longer using from memory. Use clear
to do this.
save
selectively stores variables to the disk. This is a useful technique when you are working with large amounts of data. Save data to the disk periodically, and then use the clear
function to remove the saved data from memory.
load
reloads a data file saved with the save
function.
quit
exits MATLAB and returns all allocated memory to the system. This can be useful on UNIX systems as UNIX does not free up memory allocated to an application (e.g., MATLAB) until the application exits.
Memory Allocation for Arrays | Strategies for Efficient Use of Memory |
© 1994-2005 The MathWorks, Inc.