
4 Programming
Preallocation
If you cannot vec
torize a piece of code, you can make your
for loops g o faster
by preallocatin
g any vectors or arrays in which output results are stored. For
example, this co
de uses the function
zeros to preallocate the vector created in
the
for loop. Th
is makes the
for loop execute significantly faster:
r = zeros(32,1);
for n = 1:32
r(n) = rank(magic(n));
end
Without the prea
llocation in the previous example, the M ATLAB interpreter
enlarges the
r v
ector by one elem ent each time through the loop. Vector
preallocation
eliminates this step and res ults in faster execution.
4-32
Commenti su questo manuale