function [A]=missls(X,M)
%[A]=missls(X,M)
%This function determines the least squares solution to the problem
%     X = A * M;
%by finding A according to
%     A = (X*M')/(M*M')
%where the matrix X is allowed to have NaNs.
%M must not contain any missing elements.
%Missing elements (only in X) should be denoted by 'NaN'
%You should make sure that for no row of X all entries are missing. 

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

for i=1:ix,
  if isnan(X(i,:))==0,
    A(i,:)=X(i,:)*M'/(M*M');
   else
    Id=find(~isnan(X(i,:)));
    A(i,:)=X(i,Id)*M(:,Id)'/(M(:,Id)*M(:,Id)');
  end;
end;
