function [beta,yfitted,resids,Rsq,SE]=quickOLS_omitNan(X,y,b_intercept)

% X is Txk
% y is Tx1


idnan=any([isnan(y),any(isnan(X),2)],2);
if b_intercept
    Xsel=[ones(sum(not(idnan)),1),X(not(idnan),:)];
else
    Xsel=X(not(idnan),:);
end
T=size(Xsel,1);    
ysel=y(not(idnan),:);


XprX=Xsel'*Xsel;
Xpry=Xsel'*ysel;
beta=XprX\Xpry;

if b_intercept
    XX=[ones(T,1),X];
else
    XX=X;
end

if and(nargout>1,nargout<3)
    yfitted=XX*beta;
elseif nargout>2
    yfitted=XX*beta;
    resids=y-yfitted;
    SSE=nansum(resids.^2);
    if b_intercept
        SST=nansum((ysel-mean(ysel)).^2);
    else
        SST=nansum(ysel.^2);
    end
    SE=sqrt(XprX\(SSE/(T-size(XX,2))));
    SSratio=SSE/SST;
    if SSratio>=1
        Rsq=0;
    else
        Rsq=1-SSratio;
    end
end