function [pinvX]=misspinv(X,tol)
%[pinvX]=misspinv(X,tol)
%
% 'misspinv.m'
% $ Version 0.01 $ Date 10. July 1997 $ Not compiled $
%
% This algorithm requires the presence of:
% 'misssvd.m'
%
% Copyright
% Claus A. Andersson 1995-
% claus@andersson.dk
%
% ----------------------------------------------------
%           Find the pseudoinverse of X
% ----------------------------------------------------
%
% [pinvX]=misspinv(X);
%
% The pseudo-inverse of X is found by applying the 'reversed' svd.
%
% X        : The matrix to be decomposed. If the additional argument '0' is
%            used the U,S,V model is truncated corresponding to the rank of X.
%
% It handles missing values NaNs (very dispersed, less than 15%)

% scalar ConvLim WarnLim ItMax a b i

if ~exist('tol') | isempty('tol'),
   tol=0;
end;

[U,S,V]=misssvd(X,0);
[i,j]=size(X);

if i > 1,
   s = diag(S);
elseif i == 1,
   s = S(1);
else
   s = 0;
end
if nargin < 2
   tol = max(i,j) * max(s) * eps;
end
r = sum(s > tol);
if (r == 0)
   pinvX = zeros(size(X'));
else
   s = diag(ones(r,1)./s(1:r));
   pinvX = V(:,1:r)*s*U(:,1:r)';
end


