% UNIEQUI Transforms a  matrix via unitary equivalences 
%         to tridiagonal form
%
%       T=UniEquiNorm(A)
%       Outputs the resulting tridiagonal matrix T,
%
%       [U,T,V]=UniEqui(N)
%       T is tridiagonal and A=U*T*V'
%       Raf Vandebril
%       raf.vandebril - a - cs.kleuven.be
%       Revision Date: 1/9/2008


% REMARK: To make the code better, which means more stable and less
% memory consuming, we should not make the explicit product of the
% Householder matrices, but store them in the place which became
% available after creating all the zeros in the tridiagonal matrix.
% ---> See comments in the manuscript

function [U,T,V]=UniEqui(A)
  
    % Initializations for the matrix A 
    n=size(A,1);

    if (nargout==3)
      % Also the unitary transformations are desired
      U=eye(n);
      V=eye(n);
    end
    
      

    for i=1:n-1
      
      % Use the Householder transformation from the gallery
      [v,beta,s] = gallery('house',A(i+1:n,i));
      % H = eye(n) - beta*V*V'
      % H x = s e1
      A(i+1:n,i+1:n)=A(i+1:n,i+1:n)-beta*v*v'*A(i+1:n,i+1:n);
      A(i+1,i)=s;
      A(i+2:n,i)=0;
      
      % Construct the cummulated U
      if (nargout==3)
        U(:,i+1:n)=U(:,i+1:n)-beta*U(:,i+1:n)*v*v';
      end
      
      
      [v,beta,s] = gallery('house',A(i,i+1:n)');
      A(i+1:n,i+1:n)=A(i+1:n,i+1:n)-conj(beta)*A(i+1:n,i+1:n)*v*v';
      A(i,i+1)=conj(s);
      A(i,i+2:n)=0;
 
      if (nargout==3)
        V(:,i+1:n)=V(:,i+1:n)-conj(beta)*V(:,i+1:n)*v*v';
      end
    end
    
    % Assign outputs in case of 1 or 3 arguments
    if (nargout>1)
      T=A;
    else
      U=A;
    end
    
    
