function [counts_,vals_] = xtab2(set1,set2)

%XTAB2 -- Builds (and prints) a two-way contingency table from data.
%
% XTAB2(SET1,SET2)
% COUNTS = XTAB2(SET1,SET2)
% [COUNTS,VALS] = XTAB2(SET1,SET2)
% ... = XTAB2([VAR1,VAR2])
%
% This is a specialized variant of the function XTAB for the important
% special case of two-dimensional data.
% SET1 and SET2 are column-matrices (see XTAB for details).
% The rows in either of them are treated as 'composite values'.
% The interpretation of the output arguments is the same as in XTAB.
%
% For backward compatibility, when each set contains a single variable,
% the call XTAB2([VAR1,VAR2]) can be used instead of XTAB2(VAR1,VAR2).
%
% See also XTAB, XTAB1, PRINT_XTAB, XTAB2PCORR, TABULATE, HIST, UNIQUE.

% Original coding by Alex Petrov, Ohio State University
% $Revision: 1.2 $  $Date: 2002/01/14 10:07 $
%
% Part of the utils toolbox version 1.1 for MATLAB version 5 and up.
% http://alexpetrov.com/softw/utils/
% Copyright (c) Alexander Petrov 1999-2006, http://alexpetrov.com
% Please read the LICENSE and NO WARRANTY statement in ../utils_license.m

%-- Decipher arguments
if (nargin==1)    % shorthand notation?
   [N,K1] = size(set1) ;
   if (K1~=2)
      error('DATA must be a N-by-2 matrix in the shorthand version.') ;
   end
   set2 = set1(:,2) ;
   set1 = set1(:,1) ;
%else  Assume SET1 and SET2 are correctly provided by the caller
end

[N,K1] = size(set1) ;
[N2,K2] = size(set2) ;
if (N~=N2)
   error('The two data sets must have the same number of cases (rows).') ;
end
if (N*K1*K2==0) error('Empty input argument(s).') ; end


%-- Find the unique values in each set and recode them as 1,2,...,Nk
if (K1==1)   % single variable
   [vals1,foo,keys1] = unique(set1) ;
else        % multiple variables --> composite values
   [vals1,foo,keys1] = unique(set1,'rows') ;
end
if (K2==1)   % single variable
   [vals2,foo,keys2] = unique(set2) ;
else        % multiple variables --> composite values
   [vals2,foo,keys2] = unique(set2,'rows') ;
end

%-- Intersect the (recoded) sets and count the unique pairs
[pairs,foo,keys] = unique([keys1,keys2],'rows') ;
linear_counts = hist(keys,size(pairs,1))' ;

%-- Arrange LINEAR_COUNTS into a rectangular table
n1 = size(vals1,1) ;
n2 = size(vals2,1) ;

counts = zeros(n1,n2) ;
idx = sub2ind([n1,n2],pairs(:,1),pairs(:,2)) ;    % linear index
counts(idx) = linear_counts ;

%-- Print a frequency table when no outputs are requested
if (nargout==0)
   print_xtab(counts,{vals1,vals2}) ;   
else  % export values and don't print anything
   counts_ = counts ;
   vals_ = {vals1,vals2} ;
end

%% Return COUNTS_ and VALS_
%%%%% End of XTAB2.M
