function Q = mgs(A)
%MGS Modified Gram-Schmidt orthonormalization.
%
% Q = mgs(A)
%
% Applies the modified Gram-Schmidt process to the matrix A
% (assuming that A has full rank), and returns a matrix Q whose
% columns are orthonormal and span the range of A.

% Per Christian Hansen, UNI-C, 04/11/90.

Q = A; [m,n] = size(A);

for k=1:n
   Q(:,k) = Q(:,k)/norm(Q(:,k));
   Q(:,k+1:n) = Q(:,k+1:n) - Q(:,k)*(Q(:,k)'*Q(:,k+1:n));
end
