% Phi correlation for binary variable
%        ad-bc     
% r =  -----------  
%       sqrt(efgh)  
% where the data are organized as
%
%   a  b   e
%   c  d   f
%   g  h
% a is the count of (x=0, y=0), b is the count of (x=1, y=0)
% c is the count of (x=0, y=1), c is the count of (x=1, y=1)
% e, f, g and h are the totals of the rows and columns.
%
% Each row of x should be a sample, and each column is a
% binary variable.  

function r = phi (x)

   % Get the sizes and build the result matrix

   [nr, nc] = size (x);
   

   r = zeros (nc);
   for v1 = 1:nc
      for v2 = 1:nc
         % Pull off the two vectors, and get the stats

         x1 = x(:, v1);
         x2 = x(:,v2);
         a = sum((x1==x2) & (x1==0));
         d = sum((x1==x2) & (x1==1));
         b = sum((x1~=x2) & (x1==1));
         c = sum((x1~=x2) & (x1==0));
         e = a+b;
         f = c+d;
         g = a+c;
         h = b+d;
         r(v1,v2) = (a*d-b*c)/sqrt(e*f*g*h);
      end
   end

