%
%Illustration of Smirnov's Test
clear all
close all
 disp('Smirnov Test Simulated Example')
 lw = 2; 
 set(0, 'DefaultAxesFontSize', 16);
 fs = 15;
 msize = 8;

% % randn('seed',0)
% % x = normrnd(-1 , 2, [1,  39]);
% % y = trnd(10, [1, 35]);
% %        x = sort(x); y= sort(y);
% % % 

x =[...
   -5.75    -3.89    -3.69    -3.68    -3.54    -2.59 ...
   -2.53    -2.40    -2.39    -2.27    -2.02    -1.72 ...
   -1.64    -1.54    -1.27    -1.11    -1.08    -1.00 ...
   -0.88    -0.84    -0.47    -0.36    -0.29    -0.24 ...
   -0.20    -0.19     0.02     0.15     0.25     0.45 ...
    0.51     0.72     0.74     0.96     1.25     1.33 ...
    1.49     2.39     2.59 ];

y=[...
   -2.72    -2.18    -1.31    -1.17    -1.00    -0.94 ...
   -0.78    -0.65    -0.63    -0.52    -0.40    -0.37 ...
   -0.30    -0.21    -0.19    -0.11    -0.05     0.12 ...
    0.14     0.25     0.27     0.35     0.45     0.48 ...
    0.48     0.60     0.71     0.76     0.79     1.01 ...
    1.10     1.10     1.12     1.36     2.03 ];

%%Note that both samples should be sorted, if not
% x=sort(x); y=sort(y);

m = length(x); n=length(y);
i = 1:m; j = 1:n;
distances = [i./m - empiricalcdf(x, y)   j./n - empiricalcdf(y, x)];
Dmn =  max(distances)    %0.3414

z = sqrt(m * n/(m + n))*Dmn %1.4662
pval1 = 1 - kscdf(z)    %0.0271
bmn = (m+n)/(2*m*n) * (min(m,n) - gcd(m, n))/(m + n + gcd(m,n)) %0.0123
zz =  sqrt(m * n/(m + n))*(Dmn + abs(m-n)/(6*m*n) +  bmn )   %1.5211
pval2 = 1 - kscdf(zz)  %0.0196


[h,p,k] = kstest2(x,y)
   % 1
   % 0.0202
   % 0.3414

   %

close all

xx = -7:0.01:5;
 

plot(xx, empiricalcdf(xx, x), 'r-', 'linewidth',2)
hold on
plot(xx, empiricalcdf(xx, y), 'k-','linewidth',2)
axis tight
h=legend('Emp CDF from ${\cal N}(-1,2^2)$','Emp CDF from $t_{10}$','Location','northwest')
  set(h,'Interpreter','latex')
  print -depsc 'C:\STAT1\Goodness\Goodnesseps\smirnovnt.eps'
