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.

11 Improving Performance and Memory Usage<br />

sprintf('The new value of A is %d', A)<br />

function Y = myfun(X)<br />

X(400,:) = 0;<br />

Y = X;<br />

Working with Large Data Sets. Again, when working with large data sets,<br />

you should be aware that <strong>MATLAB</strong> makes a temporary copy of A if the called<br />

function modifies its value. This temporarily doubles the memory required<br />

to store the array, which causes <strong>MATLAB</strong> to generate an error if sufficient<br />

memory is not available.<br />

One way to avoid running out of memory in this situation is to use nested<br />

functions. A nested function shares the workspace of all outer functions,<br />

giving the nested function access to data outside of its usual scope. In the<br />

example shown here, nested function setrowval has direct access to the<br />

workspace of the outer function myfun, making it unnecessary to pass a copy<br />

of the variable in the function call. When setrowval modifies the value of A, it<br />

modifies it in the workspace of the calling function. There is no need to use<br />

additional memory to hold a separate array for the function being called, and<br />

therealsoisnoneedtoreturnthemodifiedvalueofA:<br />

function myfun<br />

A = magic(500);<br />

function setrowval(row, value)<br />

A(row,:) = value;<br />

end<br />

setrowval(400, 0);<br />

disp('The new value of A(399:401,1:10) is')<br />

A(399:401,1:10)<br />

end<br />

Data Structures and Memory<br />

Memory requirements differ for the various types of <strong>MATLAB</strong> data structures.<br />

You may be able to reduce the amount of memory used for these structures by<br />

considering how <strong>MATLAB</strong> stores them.<br />

11-16

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

Saved successfully!

Ooh no, something went wrong!