clear
n=39;
nt=25;
rs = 0:0.1:1;
threshold = 0.2;
MC = 500;
C = zeros(MC,length(rs))+NaN;
for ir =1:length(rs)
  for mc=1:MC
    r=rs(ir);
    x=randn(n,nt);
    y = r*x(1,:)+sqrt(1-r^2)*randn(1,nt);

    %compute correlation between y and pool of predictors
    c = correlation(x,y(ones(n,1),:));
    %choose the ones whose correlation exceeds the threshold
    good = find(abs(c)>threshold);
    n2 = min([nt,length(good)]);
    x2 = x(good,:);

    %PCA of retained predictors
    [u,s,v] = svd(x2,'econ');
    x2 = v';

    %keep PCs whose corelation exceeds the threshold
    c2 = correlation(x2,y(ones(n2,1),:));
    good2 = find(abs(c2)>threshold);
    x3 = x2(good2,:);
    
    %cross-validated regression
    for ii=1:nt
      ind = setdiff([1:n],ii);
      b= regress(y',[x3;ones(1,nt)]');
      xp(ii) = [x3(:,ii);1]'*b;
    end
   C(mc,ir)= corr2(y,xp);
  end
  plot(rs,[rs;prctile(C,95);prctile(C,50);prctile(C,25)],'-x')
  legend('','95%','50%','25%','location','southeast')
  grid
  drawnow
end