function [A,X]=missorth(X,M)
%[A,Xm]=missorth(X,M)
%This function determines the least squares solution to the problem
%     X = A * M,     s.t. A'*A=I
%by finding A (iteratively) according to
%     A = (X*M')/((M*X'*X*M')^(1/2)) s.t. A'*A=I
%where the matrix X is allowed to contain missing elements.
%M must not contain any missing elements.
%Missing elements should be denoted as 'NaN's
%You should make sure than for no row of X, all entries are missing.
%Xm represents the full array with the NaNs replaced by the values  

[ix jx]=size(X);
[im jm]=size(M);
ia=ix;
ja=im;
A=zeros(ia,ja);

[iNaNs jNaNs]=find(isnan(X));
leniNaN=size(iNaNs,1);

if leniNaN>0,
    for i=1:leniNaN;
        X(iNaNs(i),jNaNs(i)) = mismean(jNaNs(i));
    end;
    
    Diff=Inf;
    while Diff>1e-12,
        A = (X*M')/((M*X'*X*M')^(1/2));
        Diff = 0;
        for i = 1:leniNaN,
            p = A(iNaNs(i),:)*M(:,jNaNs(i));
            Diff = Diff + ( X(iNaNs(i),jNaNs(i)) - p ).^2;
            X(iNaNs(i),jNaNs(i)) = p;
        end;
    end;
else
    A = (X*M')/((M*X'*X*M')^(1/2));
    X = A*M;
end;
