clear
N=19; %max number of predictors
nt=48; %number of years
MC = 1; %number of Monte Carlo trials
threshold = 0.2; %correlation threshold for keeping predictors
C = zeros(MC,N)+NaN;
for n=N
  for mc=1:MC
    %pick n predictors and 1 predictand
    x = randn(n,nt);
    y = randn(1,nt);

    %compute correlation between y and pool of predictors x
    c = correlation(x,y(ones(n,1),:));

    %choose the ones whose correlation exceeds the threshold
    good = find(abs(c)>threshold);
    length(good)
    %selection at most nt
    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,:);
    length(x3)

    %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,n)= corr2(y,xp)
   corr2(y,xp)
  end
%  plot([1:N],[prctile(C,95);prctile(C,50);prctile(C,25)],'-x')
%  legend('95% sig.','50th','25th','location','southeast')
%  xlabel('selection pool size')
%  grid
plot([y;xp]')
  drawnow
end