% A simple Gram Schmidt Code that
% shows the procedure and plots the
% outcomes. In order to plot outcomes
% it is limited to vectors in R^3.
clear, close all

% the following produces 3 linearly-independent
% vectors, taken as the columns of the matrix A.
% (note, you can estimate the chances of getting
% any 2 vectors or all 3 vectors being linearly
% dependent by this procedure. The probability is
% low, the challenge, however, is that the test needs
% to take into account the numerical resolution of matlab
% running on your machine).
A=randn(3);
figure(1)
hold
% plot the standard basis
quiver3(0,0,0,1,0,0,'k')
quiver3(0,0,0,0,1,0,'k')
quiver3(0,0,0,0,0,1,'k')
%plot the columns of A:
for jj = 1:3
quiver3(0,0,0,A(1,jj),A(2,jj),A(3,jj),'r')
end
view(129,-32)
fprintf('USE THE ROTATE COMMAND \n')
fprintf('ON THE FIGURE TO CONFIRM \n')
fprintf(' VECTORS ARE LINEARLY INDEPENDENT \n')
xlabel('e_y axis')
ylabel('e_x axis')
zlabel('e_z axis')

% Now we work through the GS process, but
% we will do so very explicitly. One would
% not code GS this way for the more general
% problem of finding N orthonormal vectors.

Q1=A(:,1);
q1=Q1/norm(Q1);
quiver3(0,0,0,q1(1,1),q1(2,1), q1(3,1),'linewidth',3)
Pq1=A(:,2)'*q1;
Q2=A(:,2)-Pq1*q1;
q2=Q2/norm(Q2);
quiver3(0,0,0,q2(1,1),q2(2,1), q2(3,1),'linewidth',3)
Pq1=A(:,3)'*q1;
Pq2 = A(:,3)'*q2;
Q3=A(:,3)-Pq1*q1-Pq2*q2;
q3=Q3/norm(Q3);
quiver3(0,0,0,q3(1,1),q3(2,1), q3(3,1),'linewidth',3)
title('black=standard, red=linearly independent vectors, colors=orthonormal vectors')

fprintf('confirm orthogonality of vectors:\n')
orth1=q1'*q2;
orth2=q1'*q3;
orth3=q2'*q3;
fprintf('q1.q2 = %f, q1.q3=%f, q2.q3=%f \n',orth1,orth2,orth3);
fprintf('norm(q1) = %f,norm(q1) = %f,norm(q1) = %f \n',norm(q1),norm(q2),norm(q3));

disp('hit any key to rotate view')
pause
for jj = 1:15:90
for ii = 1:15:90
    view(ii,jj)
    pause(1)
end
end