Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Include Page
SIMULATION: MATLAB Google Analytics
SIMULATION: MATLAB Google Analytics

The Need for Array Pre-Allocation

The MATLAB code analyzer produces two warnings about our x and t arrays changing size on every iteration as demonstrated in the video below.

HTML
<iframe width="600" height="338" src="//www.youtube.com/embed/N9JEnT76BKY?rel=0" frameborder="0" allowfullscreen></iframe>

The following video briefly explains why array pre-allocation leads to faster code. See this blog-post for more information about pre-allocation.

HTML
<iframe width="600" height="450" src="//www.youtube.com/embed/iSVEN_feRKA?rel=0" frameborder="0" allowfullscreen></iframe>

Pre-Allocation Procedure

We pre-allocate the x and t arrays using the zeros function as shown below.

HTML
 <iframe width="600" height="338" src="//www.youtube.com/embed/BFR8WjtYwNg?rel=0" frameborder="0" allowfullscreen></iframe> 

Change in Run-Time due to Pre-Allocation

We next use the "profiler" in MATLAB to check how much the run-time decreases due to pre-allocation.

figure(1); %Create figure #1
clf; %Clear current figure
h=plot( , ,' ');
set(h,'LineWidth',2); %Set linewidth for curve
set(gca,'Box','on','LineWidth',2,...
   'FontName','Helvetica',...
   'FontSize',14); %Set axis properties
xlabel('');
ylabel('');
title('');
axis square; %Make axis box square

figure(1); %Create figure #1
clf; %Clear current figure
h=plot(,,'');
set(h,'LineWidth',2); %Set linewidth for curve
set(gca,'Box','on','LineWidth',2,...
'FontName','Helvetica',...
'FontSize',14); %Set axis properties
xlabel('');
ylabel('');
title('');
axis square; %Make axis box square

...