% This function implements the consistent procedure
% for the determination of the number of factors described
% in the paper "Determining the number of factors from empirical
% distribution of eigenvalues"
% The inputs are:
% 1) an n by T matrix X, which has the factor structure X=LF'+e
% 2) rmax, which is a priori maximal number of factors
% The output is the number of factors
function out=onatski(X,rmax)
N=size(X,1);
T=size(X,2);
% compute the sample covariance matrix
if N<=T
S=X*X'/T;
minNT=N;
else
S=X'*X/N;
minNT=T;
end
% check that rmax is smaller enough than the sample size
if minNT=delta} or if all the differences
% are smaller than delta, set r=0. Set j=r+1.
dif=D(1:rmax)-D(2:rmax+1);
detec=flipdim(dif