% ortho.m
% to study ways to create on-bases from any base.
clear

% generate 3 random vectors, the columns of A
A=rand(3,3);
v1=A(:,1); v2=A(:,2); v3=A(:,3);

% Let us first follow Gram and Schmidt
u1=v1/norm(v1);
u2=v2-(v2'*u1)*u1; u2=u2/norm(u2);
u3=v3-(v3'*u1)*u1-(v3'*u2)*u2; u3=u3/norm(u3);
Ugs=[u1 u2 u3];
% now, u1,u2,u3 make an orthonormal basis for the space
% equivalently, Ugs is an orthogonal matrix

% our second method is by means of projections
u1=v1;
P1=v1*inv(v1'*v1)*v1'; P1perp=eye(3)-P1; u2=P1perp*v2;
P2=[v1 v2]*inv([v1 v2]'*[v1 v2])*[v1 v2]'; P2perp=eye(3)-P2;
u3=P2perp*v3;

u1=u1/norm(u1); u2=u2/norm(u2); u3=u3/norm(u3);
Uproj=[u1 u2 u3];

% our third method is by Givens rotations
alpha1=-atan(A(2,1)/A(1,1));
c=cos(alpha1); s=sin(alpha1);
Rot1=[c -s 0 ; s c 0 ; 0 0 1]; A1=Rot1*A;
alpha2=-atan(A1(3,1)/A1(1,1));
c=cos(alpha2); s=sin(alpha2);
Rot2=[c 0 -s ; 0 1 0 ; s 0 c]; A2=Rot2*A1;
alpha3=-atan(A2(3,2)/A2(2,2));
c=cos(alpha3); s=sin(alpha3);
Rot3=[1 0 0 ; 0 c -s ; 0 s c]; A3=Rot3*A2;
Urot=Rot3*Rot2*Rot1;
% note that we now have a complete QR-factoriztion of A, A=Urot'*A3

% our fourth method is by householder reflections, see householder.m

% our fifth method is by the matlab command qr
[Uqr,R]=qr(A);
% now, A=Uqr*R
% Please, use the matlab command window to study the various matrices.
% For instance, try Urot, Urot'*Urot, eig(Urot), eig(Urot).*conj(eig(Urot)), etc
