% This is a script file to illustrate loops and 
% Matlab's built-in vetorization
%
clc
disp('                         Loops and Vectorization')
disp(' ')
disp('Note: AVOID LOOPS WHENEVER POSSIBLE (perhaps not so much in MATLAB 7)')
disp('As a first example we compute the length (or 2-norm) of a random vector:')
n = input('Enter length of vector: ');
x = rand(n,1);
disp('How long does a for-loop take?')
tic;
s = 0;
for i=1:n
    s = s + x(i)^2;
end
t1 = toc;
fprintf('norm(x) = %f \n', s)
fprintf('Time with for-loop: %f seconds\n\n', t1)

disp('Now vectorized using MATLAB''s sum function:')
tic;
s = sum(x.^2);
t2 = toc;
fprintf('norm(x) = %f \n', s)
fprintf('Time vectorized with sum: %f seconds\n\n', t2)

disp('And using MATLAB''s norm function:')
tic;
s = norm(x)^2;
t3 = toc;
fprintf('norm(x) = %f \n', s)
fprintf('Time vectorized with sum: %f seconds\n\n\n', t3)

disp('Paused...Please hit a key to continue')
pause

disp('As a second example we perform matrix-vector multiplication')
n = input('Enter size of problem: ');
A = rand(n);
b = rand(n,1);
disp('How long does a double for-loop take?')
tic;
y = zeros(n,1);
for j=1:n
    for k=1:n
        y(j) = y(j) + A(j,k)*b(k);
    end
end
t1 = toc;
fprintf('Time with for-loop: %f seconds\n\n', t1)

disp('Now vectorized as a series of dot products (with single for-loop):')
tic;
y = zeros(n,1);
for j=1:n
    y(j) = A(j,:)*b;
end
t2 = toc;
fprintf('Time dot products: %f seconds\n\n', t2)

disp('Fully vectorized:')
tic;
y = A*b;
t3 = toc;
fprintf('Time vectorized: %f seconds\n', t3)

disp('Paused...Please hit a key to continue')
pause

