function [ Q, R ] = mgs ( A )
%
%  function [ Q, R ] = mgs ( A )
%
%  Purpose:
%
%    MGS carries out the modified Gram-Schmidt QR factorization method.
%
%  Modified:
%
%    10 March 2000
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, real A(M,N), the matrix whose QR factorization is desired.
%
%    Output, real Q(?,?), R(?,?), a matrix Q with orthogonal columns, and 
%    and upper triangular matrix R with the property that A = Q * R.
%
[ m, n ] = size ( A )
%
Q = zeros ( m, n );
R = zeros ( n, n );

for j = 1 : n

  t = norm ( A(:,j), 2 );
  Q(:,j) = A(:,j) / t;

  R(j,j) = t;

  for j2 = j+1 : n
    R(j,j2) = Q(:,j)' * A(:,j2);
    A(:,j2) = A(:,j2) - R(j,j2) * Q(:,j);
  end

end
