function U = cgs4 ( A, tol )

%*****************************************************************************80
%
%% cgs4() 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).
%
%    The process will reject zero vectors, as well as vectors with very
%    small remainder after the subtraction of projections of previously 
%    accepted vectors.
%
%  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.
%
%    real TOL, the acceptance tolerance.
%
%  Output:
%
%    Output, real U(M,K), a matrix with orthonormal columns.
%
  [ m, n ] = size ( A );

  k = 0;
  U = zeros ( m, k );

  for j = 1 : n

    v = A(:,j);

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

    vnorm = norm ( v );
    if ( tol < vnorm )
      v = v / vnorm;
      k = k + 1;
      U(:,k) = v;
    end
 
  end

  return
end
