Loops and Vectorization II

As a second example we perform matrix-vector multiplication

Define the size of the problem

n = 2000;

Next compute a random matrix and right-hand side vector

A = rand(n);
b = rand(n,1);

How long does a double for-loop take?

tic;                % start timer
y = zeros(n,1);     % pre-allocate to make more efficient
for j=1:n
    for k=1:n
        y(j) = y(j) + A(j,k)*b(k);
    end
end
t1 = toc;           % end timer
fprintf('Time with for-loop: %f seconds\n\n', t1)
Time with for-loop: 9.433409 seconds

Now vectorized as a series of dot products (with single for-loop)

tic;                % start timer
y = zeros(n,1);     % pre-allocate to make more efficient
for j=1:n
    y(j) = A(j,:)*b;
end
t2 = toc;           % end timer
fprintf('Time dot products: %f seconds\n\n', t2)
Time dot products: 0.067820 seconds

Fully vectorized

clear y            % start with a clean slate
tic;               % start timer
y = A*b;
t3 = toc;          % end timer
fprintf('Time vectorized: %f seconds\n\n', t3)
Time vectorized: 0.005044 seconds