function U = cgs2 ( A )

%*****************************************************************************80
%
%% cgs2() applies the classical Gram-Schmidt algorithm with normalization.
%
%  Discussion:
%
%    The output of this function will be a set of orthonormal vectors,
%    such that U(:,i) dot U(:,j) = delta(i,j).
%
%    Some vectors might be exactly zero, in which case othonormality
%    does not apply to them.
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    07 December 2019
%
%  Author:
%
%    John Burkardt
%
%  Input:
%
%    real A(M,N), a matrix of N vectors.
%
%  Output:
%
%    real U(M,N), a matrix with orthonormal columns.
%
  [ m, n ] = size ( A );

  U = zeros ( m, n );

  for j = 1 : n

    v = A(:,j);

    for j2 = 1 : j - 1
      v2 = U(:,j2);
      p = v' * v2 / norm ( v2 );
      v = v - p * v2;
    end

    vnorm = norm ( v );
    if ( 0.0 < vnorm )
      v = v / vnorm;
    end

    U(:,j) = v;
 
  end

  return
end
