% BiDiag transforms a matrix via unitary equivalence to bidiagonal form
% 
%       B=BiDiag(A)
%       Outputs a unitary equivalent bidiagonal matrix B.
%
%       [U,B,V]=BiDiag(A)
%       Outputs a bidiagonal matrix B and two unitary matrices U and V
%       such that the following relations hold A=U B V^*  
%
%
%       Raf Vandebril
%       Revision Date: 15 V 09


% REMARK: THIS CODE IS JUST A TESTCODE, THE HOUSEHOLDERS ARE NOT YET
% PERFORMED EFFICIENTLY. Just implemented as dense matrices.

function [U,A,V]=BiDiag(A)

  
  [n,m]=size(A);
  mindim=min(n,m);
  
  U=eye(n,n);
  V=eye(m,m);
  
  
  
  for cr=1:mindim-1
    Ut=house(A(cr:n,cr),n);
    A=Ut*A;
    U=Ut*U;
    
    Vt=house(A(cr,cr+1:m)',m);
    A=A*Vt';
    V=Vt*V;
    
    %  pause
  end
  
  % Perform, in case of a square matrix the final transformations
  if n>m
    Ut=house(A(m:n,m),n);
    A=Ut*A;
    U=Ut*U;
  elseif n<m    
    Vt=house(A(n,n+1:m)',m);
    A=A*Vt';
    V=Vt*V;
    
  end

  
  
  % Check the number of output arguments and assign correspondingly
  if (nargout==1)
    U=A;
  else
    U=U';
    V=V';
    
  end

  
  
  
  
%--------------------------- Function Householder transformation ------------  
  function H=house(v,n)
  
  [v,beta,s] = gallery('house',v);
  m=length(v);
  H = eye(m) - beta*v*v';
  H=blkdiag(eye(n-m),H);  