Use Nested Functions to Pass Fewer Arguments
When working with large data sets, be aware that MATLAB makes a temporary copy of an
input variable if the called function modifies its value. This temporarily doubles the
memory required to store the array, which causes MATLAB to generate an error if
sufficient memory is not available.
One way to use less memory in this situation is to use nested functions. A nested function
shares the workspace of all outer functions, giving the nested function access to data
outside of its usual scope. In the example shown here, nested function setrowval has
direct access to the workspace of the outer function myfun, making it unnecessary to
pass a copy of the variable in the function call. When setrowval modifies the value of A,
it modifies it in the workspace of the calling function. There is no need to use additional
memory to hold a separate array for the function being called, and there also is no need
to return the modified value of A:
function myfun
A = magic(500);
function setrowval(row, value)
A(row,:) = value;
end
setrowval(400, 0);
disp('The new value of A(399:401,1:10) is')
A(399:401,1:10)
end
Using Appropriate Data Storage
MATLAB provides you with different sizes of data classes, such as double and uint8, so
you do not need to use large classes to store your smaller segments of data. For example,
it takes 7 KB less memory to store 1,000 small unsigned integer values using the uint8
class than it does with double.
Use the Appropriate Numeric Class
The numeric class you should use in MATLAB depends on your intended actions. The
default class double gives the best precision, but requires 8 bytes per element of
memory to store. If you intend to perform complicated math such as linear algebra, you
must use a floating-point class such as a double or single. The single class requires
29 Memory Usage