Preallocation is an important technique that can help speed up your code. Each variable in
MATLAB must be stored in one contiguous block of memory addresses. If memory for a large
variable is not allocated at the beginning of the program, then the memory around it may be
allocated, restricting its space to expand, resulting in out of memory errors.
Example 7.2(a)
Consider the following piece of typical code that constructs a vector with 10000 elements:
%% Version 1 code
clear;
t = cputime;
x(1) = 0.31;
for i = 2:10000
x(i) = ( 1 - 1.3*x(i-1))^2;
end
elapsed1 = cputime-t
The preceding statements ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month, and much more.