MATLAB:Iterative Structures
Often in solving engineering problems you will want a program to run pieces of code several times with slightly - or possibly vastly - different parameters. The number of times to run the code may depend on some logical expression or on the number of columns in a particular matrix. For these, you will use iterative structures.
Contents
Initializing Large Vectors
One of the dangers in MATLAB's ability to automatically resize a vector is the amount of time it actually takes to do that.
Iterative Resizing
Consider the following:
clear
tic
y0 = 0;
v0 = 5;
a = -9.81;
NP = 10;
t = linspace(0, 5, NP)
for k=1:NP
y(k) = y0 + v0*t(k) + 0.5*a*t(k).^2;
end
toc
This code takes, on average, 36 microseconds to run. If NP is increased to 100, the average time to complete goes up to about 150 microseconds. NP of 1000 increases the time to 2.25 ms. And NP of 10000 increases the time to over 10 s! The graph below shows, on a log scale, time to complete as a function of NP:
Clearly, this becomes a major problem as the number of points increases.
Initialized
Remarkably, adding a single line completely changes the timing of the program. The following program:
clear
tic
y0 = 0;
v0 = 5;
a = -9.81;
NP = 10;
t = linspace(0, 5, NP)
y = t*0; % here's the only thing that changed!!!
for k=1:NP
y(k) = y0 + v0*t(k) + 0.5*a*t(k).^2;
end
toc
generates the following time vs. NP graph:
which indicates a reduction, by three orders of magnitude, of the run time. And all that was done was creating a vector y of the appropriate size before running the loop, rather than continuously changing the vector size inside the loop.
Vectorized
Of course, the fastest version of the code uses MATLAB's ability to vectorize:
clear
tic
y0 = 0;
v0 = 5;
a = -9.81;
NP = 10;
t = linspace(0, 5, NP)
y = y0 + v0*t + 0.5*a*t.^2;
toc
which generates the following time vs. NP graph:
Questions
Post your questions by editing the discussion page of this article. Edit the page, then scroll to the bottom and add a question by putting in the characters *{{Q}}, followed by your question and finally your signature (with four tildes, i.e. ~~~~). Using the {{Q}} will automatically put the page in the category of pages with questions - other editors hoping to help out can then go to that category page to see where the questions are. See the page for Template:Q for details and examples.