function Q = modified_gs( X )
% Q = modified_gs( X ) computes the modified Gram-Schmidt
% orthogonalization of the columns of X regarded
% as vectors.  The resulting orthonormal set
% is returned as the columns of Q.  The matrix Q might have
% fewer columns than X.

% M. M. Sussman
% $Date: 2017/03/14 19:03:18 $

nx=size(X,2);

nq=0;
for k=1:nx
  y=X(:,k);
  for ell=1:nq
    rlk=dot(Q(:,ell),y);
    y=y-rlk*Q(:,ell);
  end
  rkk=norm(y);
  % if rkk is zero, then column k of X is linearly dependent
  % on the previous columns and cannot be orthogonal to them.
  if rkk > 0
    nq=nq+1;
    Q(:,nq)=y/rkk;
  end
end
