
484 Accelerating MATLAB
®
Performance
This solution is useful when the nal size is known in advance, as the following snippet
illustrates:
% This is run on MATLAB 7.12 (R2011a):
% Regular dynamic array growth:
f=[0,1]; for idx=3:40000, f(idx)=f(idx-1)+f(idx-2); end
⇨ Elapsed time is 0.019954 seconds.
% Now use preallocation - 5x faster than dynamic array growth:
f=zeros(40000,1); f(1)=0; f(2)=1;
for idx=3:40000, f(idx)=f(idx-1)+f(idx-2); end
⇨ Elapsed time is 0.004132 seconds.
On pre-R2011a releases the effect of preallocation is even more pronounced:
% This is run on MATLAB 7.1 (R14 SP3):
% Regular dynamic array growth:
f=[0,1]; for ...