% plots absolute and relative errors in singular values

clc;
clear all;
close all;

% matrix dimensions
n=[50 100 200 300];
% Sparse matrix generation
r=10:5:20; %in percentage the number of non zero elemements
f=0;

% loop starts from here
for i=1:length(r)
    for j=1:length(n)
        % number of non zero elements
        m=n(j)*n(j)*r(i)/100;
        % randomizing indices
        x=randi(n(j),1,m);
        y=randi(n(j),1,m);
        % generating elements
        z=randn(1,m);
        % Matrix generation
        A=sparse(x,y,z,n(j),n(j));
        A=full(A);
        
        % Decompositions
        
        % built-in SVD decomposition
        
        [u1,d1,v1]=svd(A);        
        [x,y]=size(d1);
        
        % SVDecom
        
        [u2,d2,v2]=SVDecom(A);
        
        % mp_mysvd
        
        [d3]=SVD(A);
                
        a=diag(d1);
        
        f=f+1;
        h=figure(f);
        hold on
        loglog(a,abs(a-diag(d2)),'g^-','MarkerFaceColor','g','LineWidth',2);
        loglog(a,abs(a-(d3)),'ks-','MarkerFaceColor','k','LineWidth',2);
        grid
        axis tight
        xlabel('\sigma_i');
        ylabel('e_i');
        title(['Comparison of absolute error in sigular values for ',num2str(n(j)),' x ',num2str(n(j)),' Sparse matrix of ',num2str(r(i)),' % non-zero elements']) ;
        legend('Indirect Method','Direct Method');
        print(h,'-dpng');
        
        f=f+1;
        h=figure(f);
        hold on
        scatter (a,abs(a-diag(d2)),'g','filled')
        scatter (a,abs(a-(d3)),'k','filled')
        axis tight
        xlabel('\sigma_i');
        ylabel('e_i');
        title(['Comparison of absolute error in sigular values for ',num2str(n(j)),' x ',num2str(n(j)),' Sparse matrix of ',num2str(r(i)),' % non-zero elements']);
        legend('Indirect Method','Direct Method');
        print(h,'-dpng');
        
        f=f+1;
        h=figure(f);
        hold on
        loglog(a,abs(a-diag(d2))./a,'g^-','MarkerFaceColor','g','LineWidth',2);
        loglog(a,abs(a-(d3))./a,'ks-','MarkerFaceColor','k','LineWidth',2);
        grid
        axis tight
        xlabel('\sigma_i');
        ylabel('e_i');
        title(['Comparison of relative error in sigular values for ',num2str(n(j)),' x ',num2str(n(j)),' Sparse matrix of ',num2str(r(i)),' % non-zero elements']) ;
        legend('Indirect Method','Direct Method');
        print(h,'-dpng');
        
        f=f+1;
        h=figure(f);
        hold on
        scatter (a,abs(a-diag(d2))./a,'g','filled')
        scatter (a,abs(a-(d3))./a,'k','filled')
        axis tight
        xlabel('\sigma_i');
        ylabel('e_i');
        title(['Comparison of relative error in sigular values for ',num2str(n(j)),' x ',num2str(n(j)),' Sparse matrix of ',num2str(r(i)),' % non-zero elements']);
        legend('Indirect Method','Direct Method');
        print(h,'-dpng');
        
    end
    
end