% example 5 for section 6.4: Gram-Schmidt orthogonalization
% Form QR factorization
A = [1 -2 -3; 2 0 -3; 2 4 3]
% Step 1: The 1st vector Q(:,1) for orthogonal basis
Q(:,1) = A(:,1)
% Normalize Q(:,1) to make it for orthonormal basis
R(1,1) = norm(Q(:,1))
Q(:,1) = Q(:,1)/R(1,1)
% Step 2: The 2nd vector Q(:,2) for orthogonal basis
R(1,2) = Q(:,1)' * A(:,2)
Q(:,2) = A(:,2) - Q(:,1) * R(1,2)
% Normalize Q(:,2) to make it for orthonormal basis
R(2,2) = norm(Q(:,2))
Q(:,2) = Q(:,2)/R(2,2)
% Step 3: The 3rd vector Q(:,3) for orthogonal basis
R(1:2,3) = Q(:,1:2)' * A(:,3)
Q(:,3) = A(:,3) - Q(:,1:2) * R(1:2,3)
% Normalize Q(:,3) to make it for orthonormal basis
R(3,3) = norm(Q(:,3))
Q(:,3) = Q(:,3)/R(3,3)
% Complete QR factorization
Q * R
Q' * Q
Q * Q'
