%% Demonstrating Efficiency

%% Loops are bad
clear;

reps = 100;
x = rand(100000,1);
y = rand(size(x));

tloop = cputime;
for r=1:reps
    s = 0;  
    for i=1:numel(x)
        s = s+x(i)*y(i);
    end
    tloop = cputime-tloop;
end
tvec = cputime;
for r=1:reps
    svec = x'*y;
end
tvec = cputime-tvec;

fprintf('loop: s=%20.16g, t=%3d\n vec: s=%20.16g, t=%3d\n' ...
        ,s,tloop,svec,tvec);
    
%% Preallocate arrays
reps = 500;
tic
for r=1:reps
    a(r,:) = rand(1,1000);
end
toc
clear a;

tic
a = zeros(reps,1000);
for r=1:reps
    a(r,:) = rand(1,1000);
end
toc
   
%% Memory layout can matter
reps = 100;
x = rand(1000,1000);
y = rand(size(x,2),1);
yp= y';
tic
for r=1:reps
    for i=1:size(x,1)
        s = yp*x(:,i);
    end
end
toc

tic
for r=1:reps
    for i=1:size(x,1)
        s = x(i,:)*y;
    end
end
toc
