Skip to main content

13.9) Writing Efficient Code


  • Define all your arrays before you use them, even if they are empty, E.g., zero(360,180), A=zeros(100,1). This is called pre-allocation
    • Undefined arrays may grow inside loops. This is undesirable as every time the array has to increase in size (by 1 cell), this involves creating a new array and copying the old array into it. It is very slow and inefficient
  • Avoid loops wherever possible
  • Use the Matlab commands tic and toc to time your commands:

[matlab]
% No Pre-Allocation
>> tic
>> for i=1:100
>> for j=1:100
>> output(i,j)=rand;
>> end
>> end
>> toc
time=0.0029s
[/matlab]
[matlab]
% No Pre-Allocation of Output
>> tic
>> output=zeros(100,100);
>> for i=1:100
>> for j=1:100
>> output(i,j)=rand;
>> end
>> end
>> toc
time=0.0005s (X6 speed-up)
[/matlab]
[matlab]
% No "for" Loops
>> tic
>> output=rand(100,100);
>> toc
time=0.0001s (X30 speed-up)
[/matlab]