function [Q, R] = GramSchmidt(A)
% Gram-Schmidt factorization.
[m, n] = size(A);
Q = zeros(m, n);
R = zeros(m, n);
for i = 1:n
    Q(:, i) = A(:, i);
    for j = 1:i-1         
        R(j, i) = dot(Q(:, j), A(:, i));
        Q(:, i) = Q(:, i) - R(j, i) * Q(:, j);
    end
    R(i, i) = norm(Q(:, i));
    Q(:, i) = Q(:, i) / R(i, i); 
end
end