
function test_svd

warning off;

ordV=2.^(0:8);
ntest=5;
cpu_metV=[];
res_metV=[];

for itest=1:length(ordV)
    
    ord=ordV(itest);
    
    x=linspace(0,1,4*ord); x=x';
    A=[];
    for j=1:ord+1
        A(:,j)=x.^(j-1);
    end
    b=rand(4*ord,1);
    lmin=min(eig(A'*A));
    
    for method_type=1:3
        tic;
        for i=1:ntest
            switch method_type
                case 1
                    if lmin > 10^(-15)
                    x=metodo_chol(A,b);
                    else
                        x=realmax*ones(ord+1,1);
                    end
                case 2
                    x=metodo_QR(A,b);
                case 3
                    x=metodo_SVD(A,b);
            end
        end
        T=toc;
        cpu_metV(itest,method_type)=T/ntest;
        res_metV(itest,method_type)=norm(b-A*x);
    end
    
end
ordV
cpu_metV

for ii=1:length(ordV)
    fprintf('\n \t $%4.0f times %4.0f$ & $%1.1e$ & $%1.1e$ & $%1.1e$ gnral',...
        4*ordV(ii),ordV(ii),cpu_metV(ii,1),cpu_metV(ii,2),cpu_metV(ii,3));
end


fprintf('\n \t ----- \n \n');

for ii=1:length(ordV)
    fprintf('\n \t $%4.0f times %4.0f$ & $%1.1e$ & $%1.1e$ & $%1.1e$ gnral',...
        4*ordV(ii),ordV(ii),res_metV(ii,1),res_metV(ii,2),res_metV(ii,3));
end


function x=metodo_chol(A,b)

B=A'*A;
R=chol(B);
c=A'*b;
y=R\c;
x=R'\y;


function x=metodo_QR(A,b)

[Q,R]=qr(A);
c=A'*b;
y=R'\c;
x=R\y;


function x=metodo_SVD(A,b)

[U,S,V] = svd(A);
x=sum(diag((U(:,1:size(A,2)))'*b./diag(S))*V);
x=x';
