function [X,flag] = pinvrd(A,tol)
%PINVRD pseudo inverse with rank deficiency detection.
% [X,flag] = PINVRD(A) produces a matrix X of the same dimensions
% as A' so that A*X*A = A, X*A*X = X and A*X and X*A
% are Hermitian. The computation is based on SVD(A) and any
% singular values less than a tolerance are treated as zero.
% The default tolerance is MAX(SIZE(A)) * NORM(A) * EPS.
% If A is not full rank flag=1 else flag=0
% PINVRD(A,TOL) uses the tolerance TOL instead of the default.
% See also RANK.
% Copyright (c) 1984-98 by The MathWorks, Inc.
% $Revision: 5.7 $ $Date: 1997/11/21 23:38:41 $
[U,S,V] = svd(A,0);
[m,n] = size(A);
if m > 1, s = diag(S);
elseif m == 1, s = S(1);
else s = 0;
if nargin < 2
tol = max(m,n) * max(s) * eps;
r = sum(s > tol);
if r<min(m,n); flag=1; else; flag=0; end;
if (r == 0)
X = zeros(size(A'));
s = diag(ones(r,1)./s(1:r));
X = V(:,1:r)*s*U(:,1:r)';