function [Q,R]=qr_gs(A);
% QR_GS Implementation of the pseudo code for the modified Gram-Smidth
% process for computing the QR decomposition on page 237 in Gilbert Strand
% Introduction to linear algebra. 
% [Q,R]=qr_gs(A)
% On input
% A - A real (m x n) matrix.
% On output
% Q - An (m x n) orthogonal matrix with orthonormal columns
% R - An (n x n) upper triangular matrix

[m,n]=size(A);
Q=zeros(m,n);
Q(:,1)=A(:,1);
R=zeros(n,n);

for j=1:n
    v=A(:,j);
    for i=1:j-1
        R(i,j)=Q(:,i)'*v;
        v=v-R(i,j)*Q(:,i);
    end
    R(j,j)=norm(v);
    Q(:,j)=v/R(j,j);
end