%
% comparision of the three methods for LS problems
%

clear all;
close all;

NN = 500:500:4000;
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***** n=%d *****\n', n);
    fprintf('Cond2(A)=%.2e\n', cond(A));

    % Cholesky
    t0 = clock;
    x1 = (A'*A)\(A'*b);
    tt(k,1) = etime(clock,t0);
    fprintf('Cholesky: time=%.4f\n', tt(k,1));
    
    % QR
    t0 = clock;
    % x2 = A\b;
    [Q,R] = qr(A,0);
    x2 = R\(Q'*b);
    tt(k,2) = etime(clock,t0);
    fprintf('QR      : time=%.4f, relerr=%.2e\n', tt(k,2), 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     : time=%.4f, relerr=%.2e\n', tt(k,3), norm(x3-x1)/norm(x1));
end
