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

preallocating the maximum amount of space that would be required for the<br />

array ahead of time.<br />

The following code creates a scalar variable x, and then gradually increases<br />

the size of x in a for loop instead of preallocating the required amount of<br />

memory at the start:<br />

x = 0;<br />

for k = 2:1000<br />

x(k) = x(k-1) + 5;<br />

end<br />

Change the first line to preallocate a 1-by-1000 block of memory for x<br />

initialized to zero. This time there is no need to repeatedly reallocate memory<br />

and move data as more values are assigned to x in the loop:<br />

x = zeros(1, 1000);<br />

for k = 2:1000<br />

x(k) = x(k-1) + 5;<br />

end<br />

Preallocation Functions<br />

Preallocation makes it unnecessary for <strong>MATLAB</strong> to resize an array each time<br />

you enlarge it. Use the appropriate preallocation function for the kind of<br />

array you are working with.<br />

Array Type Function Examples<br />

Numeric zeros y = zeros(1, 100);<br />

Cell cell B = cell(2, 3);<br />

B{1,3} = 1:3;<br />

B{2,2} = 'string';<br />

Preallocating a Nondouble Matrix<br />

When you preallocate a block of memory to hold a matrix of some type other<br />

than double, avoid using the method<br />

A = int8(zeros(100));<br />

11-8

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

Saved successfully!

Ooh no, something went wrong!