14:440:127– Introduction to Computers for Engineers
Notes for Lecture 08
Rutgers University, Fall 2009
Instructor- Blase E. Ur
1
Finishing Up Loops- Efficiency Concerns
In Matlab, you’ll often hear that it’s bad to use loops when you could have instead used vector or matrix functions.
This is because Matlab’s built-in functions and arithmetic operations are optimized to use data stored as vectors
or matrices in memory.
Thus, whenever possible, use vectors, matrices, and their associated functions.
Many of
the examples I’ve given you in this lecture and the previous lecture could be written more efficiently using built-in
functions and by ”vectorizing” (replacing loops with vector operations). I’ve given you many examples using loops
for two reasons. First of all, they’re often some of the simplest loops to write, and thus they serve a pedagogical
purpose. As you start writing more complicated programs, you’ll often need to write loops, but these loops will be
implementing much more complex algorithms. Second, most computer programming languages use loops much more
extensively than Matlab, so being good at loops is a skill-set that you can port to other languages you learn. As
with natural (human) languages, learning more programming languages becomes easier after your first one or two!
1.1
Timing Efficiency- Tic and Toc
Matlab has two convenient commands that let you time how long an operation takes to compute.
To start (and
reset) a timer, use the command
tic;
. To stop the timer and display the amount of time elapsed, use
toc;
. If you’ve
brainstormed a few different methods for solving a problem and want to have an idea of which method runs most
quickly in Matlab, use
tic
and
toc
!
1.2
Loops, Pre-allocated Memory Loops, Vector Operations
As an example of the huge differences in efficiency between methods in Matlab, let’s compare three different methods
of performing the same operation in Matlab. Particularly, let’s create a 10,000 element vector filled with the number
5
. Indeed, 5 is against the law. (That’s not actually true, that’s just what happens when you type
”5 is”
into Google
and look at the list of auto-complete possibilities.)
First, we can use the totally naive method and create this vector one element at a time:
% Allocate memory one element at a time
clear;clc
tic
for z = 1:10000
x(z) = 5;
end
toc
This method takes
0.181933 seconds
on my desktop.
Now, let’s pre-allocate memory for the vector we’re creating.
By this, we mean that we want to create a ma-
trix full of zeros that’s the eventual size we want. That way, Matlab will set aside space in memory for the entire
vector, rather than having to mess around with allocating memory each time. If you’re interested in this subject,
I’d recommend you take more advanced classes in Computer Engineering or Computer Science such as Architecture,
Operating Systems, and Compilers.