function [Q,R]=ModifiedGramSchmidt2(A);
% MODIFIEDGRAMSCHMIDT2 modified Gram-Schmidt orthogonalization version 2
%   [Q,R]=ModifiedGramSchmidt2(A); computes the modified Gram-Schmidt
%   orthogonalization of the vectors in the columns of the matrix A by
%   immediately updating all the remaining vectors as well during the
%   process

[m,n]=size(A); R=zeros(n);
for k=1:n
  R(k,k)=norm(A(:,k));
  Q(:,k)=A(:,k)/R(k,k);
  R(k,k+1:n)=Q(:,k)'*A(:,k+1:n);
  A(:,k+1:n)=A(:,k+1:n)-Q(:,k)*R(k,k+1:n);
end