%QR factorization of matrix A = [v1,v2,v3]
%v1,v2,v3 are the *linearly independent* columns of the matrix A
%the algorithm below finds the QR factorization of A via Gram-Schmidt

Q = [];
R = [];

%define columns of A

v1 = [1;1;0]  
v2 = [1;0;1]
v3 = [0;1;1]

%start Gram Schmidt and QR factorization
%the columns of Q are the vectors u1,u2,u3 found from Gram Schmidt
%R is upper triangular, and the (i,j)th entry of R is R(i,j) = dot(vj,ui) for j>=i
%the (i,i)th entry of R is the normalization of ui during Gram Schmidt

u1 = v1;
n1 = norm(u1);     %norm(x) = ||x||
u1 = u1/n1;        
R(1,1) = n1;       

u2 = v2 - dot(v2,u1)*u1;
n2 = norm(u2);         
u2 = u2/n2;            
R(1,2) = dot(v2,u1);
R(2,2) = n2;          

u3 = v3 - dot(v3,u1)*u1 - dot(v3,u2)*u2;
n3 = norm(u3);         
u3 = u3/n3;            
R(1,3) = dot(v3,u1);
R(2,3) = dot(v3,u2);
R(3,3) = n3;

%Note: each dot product dot(vj,ui) only needs to be computed *once* in this process
%(in the code above they are computed twice only for pedagogical clarity)      

Q = [u1,u2,u3];     %columns of Q = vectors u1,u2,u3
A = [v1,v2,v3];     %columns of A = original vectors v1,v2,v3

A          
Q
R  