function  [groups,vals] = split(data,split_vars)

% SPLIT  -- splits an array of data into groups; returns a cell array
%
% GROUPS = SPLIT(DATA)
% GROUPS = SPLIT(DATA,SPLIT_VARS)
% [GROUPS,VALS] = SPLIT(DATA)
% [GROUPS,VALS] = SPLIT(DATA,SPLIT_VARS)
%
% DATA is a column-oriented data set (a two-dimensional matrix).
% When the second argument is supplied, it should be a matrix with 
% the same number of rows as DATA. When not supplied, SPLIT_VARS
% defaults to DATA(:,1).  Data records (rows in DATA) belong to the 
% same group iff they have the same value(s) on the split variable(s).
%
% VALS is a matrix of unique split values. Its columns correspond
% to the variables (columns) in SPLIT_VARS. Its rows are sorted.
% GROUPS is a cell array such that GROUPS{k} contains the subset 
% of DATA corresponding to VALS(k,:).
%
% Example:  [groups,keys] = split([3 10; 2 20 ; 3 12 ; 2 21 ; 3 11])
%   groups{1} = [2 20 ; 2 21]
%   groups{2} = [3 10 ; 3 12 ; 3 11]
%   keys = [2 3]
%
% See also AGGREG, RECODE, SUMSQ, XTAB.

% Original coding by Alex Petrov, Ohio State University
% $Revision: 1.1 $  $Date: 2002/01/19 16:00 $
%
% 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

%---  Handle input arguments
if (nargin < 1 | nargin > 2)
  error('Bad number of input arguments to SPLIT.') ;
end

if (nargin == 1)
  split_vars = data(:,1) ;
elseif (size(split_vars,1)~=size(data,1))
  error('SPLIT_VARS and DATA must have the same number of rows.') ;
end

%---  Partition into groups
[vals,val_idx,keys] = unique(split_vars,'rows') ;
N = size(vals,1) ;
groups = cell(N,1) ;
for k = 1:N
  idx = find(keys==k) ;
  groups{k} = data(idx,:) ;
end

%--- Return GROUPS and, possibly, VALS
%%%%% End of SPLIT.M
