function  stats = aggreg(groups,func)

%AGGREG -- Apply a user-specified aggregation function to groups of data.
%
% STATS = AGGREG(GROUPS,FUNCTION)
%
% Analogous to MAPCAR in LISP:  STATS(K,:) = FEVAL(FUNC,GROUPS{K})
%
% GROUPs is a cell array of matrices (usually produced by SPLIT).
% FUNCTION is a string naming a function mapping matrices to numbers.
% It can also be an inline object (see INLINE and FEVAL).
% When not supplied, FUNCTION defaults to 'mean'.
%
% Example:  median_RT = aggreg(split(RT,[subject,condition]),'median')
%
% BUG: When groups{k} is a row vector, STATS columns get confounded.
% Use expressions such as aggreg(groups,inline('mean(x,1)')) to avoid that.
%
% See also SPLIT, FEVAL.


% Original coding by Alexander Petrov, Ohio State University.
% $Revision: 1.1 $  $Date: 2002/12/19 17:20 $
%
% 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 arguments
if (nargin < 1 | nargin > 2)
  error('Bad number of input arguments to AGGREG.') ;
end

if (nargin == 1)
  func = 'mean' ;          % default
elseif  (ischar(func))     % function name (the typical case)
  func = deblank(func) ;   % remove any whitespace chars from the string
elseif  (~isa(func,'inline'))
  error('FUNCTION must be either a string or an inline object.') ;
end

%---  Collect aggregates
n = length(groups) ;
stats = zeros(n,size(groups{1},2)) ;

for k = 1:n
  stats(k,:) = feval(func,groups{k}) ;
  %% BUG: When groups{k} is a single row vector, columns get confounded.
end

%--  Return STATS
%%%%% End of AGGREG.M
