function [r2,mrse,yf,res,coeff,TXT]=mplregLeaveOneOut(X,Y)
%mpl regression and performs leave-one-out validation accordingly
%Usage:
%[r2,mrse,yf,res,coeff,Q2_LOO,RMSE_LOO,RE_LOO]=mplregLeaveOneOut(X,Y)
%
%Inputs:
%X(n*m)         :m independent variables
%Y(n)           :dependend variable
%
%Outputs:
%r2             : variation explained
%rmse           : root of the mean squared error
%res            : residuals
%coeff          : coefficients of constant + nterms in predicting model
%Q2             : Q2 statistic. Good models have positive Q2, bad models
%                 negative value. Can become smaller than -1!
%RMSEP          : Validation RMSE of Prediction
%REP            : Validation relative error of Prediction.
% Is also used in the mplregstep function.
%uses mplreg

a=find(~isnan(mean(X,2)) & ~isnan(Y));
b=find(isnan(mean(X,2)) | isnan(Y));
X=X(a,:); Y=Y(a);

n=size(X,1);
ALL_E=1:n;


for EOI=1:n    
    ELEMENTS=ALL_E;
    ELEMENTS(EOI)=[];%remove EOI from calibration set
    x=X(ELEMENTS,:);
    y=Y(ELEMENTS,:);
    [r2,mrse,yf,res,coeff]=mplreg(x,y,'no');%Calibrate!
    %Add fitted constant and sum of fitted parameters times variate values
    YF=coeff(1) + X(EOI,:) * coeff(2:end,1);
    %Determine residual
    RES(EOI)=Y(EOI)-YF;
    
    %fprintf(1,'Calib R2: %5.2f  Elem %d Error: %5.2f \n', r2,EOI,RES(EOI));
end

[r2,rmse,yf,res,coeff]=mplreg(X,Y,'yes');%Calibrate based on all elements!

fprintf(1,'CALIBRATION STATS R2: %5.2f, RMSE: %5.2f.  \n', r2,rmse);

tstat = regstats(Y,X,'linear','tstat');
s=['P-VALUES for constant and coefficients: ' repmat('%5.4f, ',1,length(tstat.tstat.pval')) '\n'];
fprintf(1,s,tstat.tstat.pval');

%VALIDATION STATS
[Q2, RMSEP,REP, TXT]=CalculateQ2(Y,RES);



