% An experiment to determine the effect of digital massage and hyperosmolarity 
% on vitreous weight
% was conducted by Galin et al. (1971). The results had implications in 
% the context of cataract surgery. The authors measured
% the vitreous body weight for each eye of 15 New Zealand albino rabbits.
% One eye was treated ($y$), while the other served as a control ($x$).
% The measurements  are provided next:
% 
% Galin, M. A., Robbins, R., and Obstbaum, S. (1971).
% Prevention of vitreous loss. {\it Brit. J. Ophthal.},{\bf 55}, 533--537.

x=[1848 1532 1460 1947 1810 1718 1686 1617 ...
               1724 1873 1928 2226 1708 1605 1822];
y=[1738 1440 1388 1756 1692 1629 1583 1499 ...
               1596 1794 1785 2044 1602 1491 1702];

n=15

%nc-number of concordant pairs, 
%nd - discordant
%nt - ties
nc = 0; nd = 0; nt=0;
for i = 1:n-1
    for j = i+1:n
      if           sign(x(i) - x(j)) * sign(y(i) - y(j))  > 0     nc=nc+1;
      elseif   sign(x(i) - x(j)) * sign(y(i) - y(j))  < 0    nd=nd+1;  
      else   nt=nt+1;
      end
    end
end  
tau = (nc-nd)/(nc+nd)                        %0.9048
% OR 
%tau =corr(x', y', 'type','Kendall')  %0.9048
nc %100
nd %5
nt  %0
%Sample variance of tau
% c(i)  # of pairs concordant with the pair i
c = zeros(1,n);
for   i = 1:n
    for j = 1:n
        if i == j  continue
        else c(i)=c(i) + (sign(x(i) - x(j)) * sign(y(i) - y(j))  > 0);
        end
    end
end
%c =[14, 14, 14, 12, 14, 13, 14, 14, 12, 12, 12, 14, 13, 14, 14];
sig2 = 4*sum(c.^2) -2*sum(c) -2*(2*n-3)*(sum(c))^2/(n*(n-1))
   % 26.2857
   
 %confidence interval
[max(-1,tau  - 2/(n*(n-1)) * norminv(0.975)*sqrt(sig2)), ...
          min(1,tau  + 2/(n*(n-1)) * norminv(0.975)*sqrt(sig2))] 
  %  0.8091    1.0000     
T=nc-nd   %95
p = 2 * (1-normcdf(3*(abs(T)+1)*sqrt(2)/sqrt(n*(n-1)*(2*n -5))  ))      
%1.8965e-008


