
% Function to do Gram-Schmidt renormalization using QR
% RCG, OCt'15
%
%Usage:
% V=GS_rcg(M)
%gives the GS based V (columns) for the imput base M (comuns)
%
%Example:
% M=[2 0.5 ;  1.5 1]
% V=GS_rcg(M)

function [Q,R]=GS_rcg(M)
lw=2;

[Q,R]=qr(M);

N=length(M);
Q=Q./kron(sign(M(1,:)).*sign(Q(1,:)),ones(N,1));

if(N==2)
 figure(1);clf
 xM1=[0 M(1,1)]; yM1=[0 M(2,1)]; xM2=[0 M(1,2)]; yM2=[0 M(2,2)];
 xQ1=[0 Q(1,1)]; yQ1=[0 Q(2,1)]; xQ2=[0 Q(1,2)]; yQ2=[0 Q(2,2)];
 plot(xM1,yM1,'bo-',xM2,yM2,'bo-','LineWidth',lw)
 hold on
 plot(xQ1,yQ1,'ro-',xQ2,yQ2,'ro-','LineWidth',lw)
 hold off
 axis equal
end
 
if(N==3)
 figure(1);clf
 xM1=[0 M(1,1)]; yM1=[0 M(2,1)]; zM1=[0 M(3,1)]; 
 xM2=[0 M(1,2)]; yM2=[0 M(2,2)]; zM2=[0 M(3,2)];
 xM3=[0 M(1,3)]; yM3=[0 M(2,3)]; zM3=[0 M(3,3)];
 xQ1=[0 Q(1,1)]; yQ1=[0 Q(2,1)]; zQ1=[0 Q(3,1)]; 
 xQ2=[0 Q(1,2)]; yQ2=[0 Q(2,2)]; zQ2=[0 Q(3,2)];
 xQ3=[0 Q(1,3)]; yQ3=[0 Q(2,3)]; zQ3=[0 Q(3,3)];
 plot3(xM1,yM1,zM1,'bo-',xM2,yM2,zM2,'bo-',xM3,yM3,zM3,'bo-','LineWidth',lw)
 hold on
 plot3(xQ1,yQ1,zQ1,'ro-',xQ2,yQ2,zQ2,'ro-',xQ3,yQ3,zQ3,'ro-','LineWidth',lw)
 hold off
 axis equal
end

end

