function Q = orth(A)
%ORTH	Orthogonalization.
%	Q = orth(A) is an orthonormal basis for the range of A.
%	Q'*Q = I, the columns of Q span the same space as the columns
%	of A and the number of columns of Q is the rank of A.
%
%	See also QR, NULL.

%	C.B. Moler 11-24-85
%	Copyright (c) 1984-93 by The MathWorks, Inc.

% QR decomposition
[Q,R,E]=qr(A);
% Determine r = effective rank
tol = eps*norm(A,'fro');
r = sum(abs(diag(R)) > tol);
r = r(1); % fix for case where R is vector.
% Use first r columns of Q.
if r > 0
   Q = Q(:,1:r);
   % Cosmetic sign adjustment
   Q = -Q;
   Q(:,r) = -Q(:,r);
else
   Q = [];
end
