%
% comparision of the three methods for LS problems
%

clear all;
close all;

NN = 500:500:5000;
length_NN = length(NN);
tt = zeros(length_NN,3); % elapsed time
for k = 1:length_NN
    n = NN(k);
    m = 2*n;
    A = randn(m,n);
    b = randn(m,1);
    
    fprintf('***** n=%d *****\n', n);
    % normal equation
    t0 = clock;
    x1 = (A'*A)\(A'*b);
    tt(k,1) = etime(clock,t0);
    
    % QR
    t0 = clock;
    % x2 = A\b;
    [Q,R] = qr(A,0);
    x2 = R\(Q'*b);
    tt(k,2) = etime(clock,t0);
    fprintf('QR: relerr=%.2e\n', norm(x2-x1)/norm(x1));
    
    % SVD
    t0 = clock;
    [U,S,V] = svd(A,'econ');
    x3 = V*(diag(S).\(U'*b));
    tt(k,3) = etime(clock,t0);    
    fprintf('SVD: relerr=%.2e\n\n', norm(x3-x1)/norm(x1));
end
