% Kendall's Tau correlation function
%           6 Q
% r = 1 - -----------------
%           n (n - 1)

% Each row of x should be a sample, and each column is a
% variable.

function r = kendall (x)

   % Get the sizes and build the result matrix

   [nr, nc] = size (x);

   r = zeros (nc, nc);
   for v1 = 1:nc
      for v2 = 1:nc 

         % Pull off the two vectors, order the first and get the counts.

         x1 = x (:, v1);
         x2 = x (:, v2);
         
         % Get the sorted x1 and the indexes to use to get the sorted x2
         
         [y1, ind] = sort (x1);
         y2 = x2(ind);
         Q = 0;
         for ct = 1:nr-1
             Q = Q + sum (y2 (ct) > y2 (ct+1:nr));
         end
         r (v1, v2) = 1 - (4 * Q)/(nr * (nr - 1)); 
      end
   end

