%% Apply Function to Groups of Rows
% Create a table, A, where g is a grouping variable.

rng('default')
g = randi(3,[15,1]);
x = rand([15,1]);
y = rand([15,1]);

A = table(g,x,y)

%
% Define the anonymous function, func, to compute the average difference between x and y.

func = @(x,y) mean(x-y);

%
% Find the average difference between variables in groups 1, 2, and 3 defined by the grouping variable, g.

B = rowfun(func,A,...
    'GroupingVariable','g',...
    'OutputVariableName','MeanDiff')

% The variable GroupCount indicates the number of rows in A for each group.
% Copyright 2012 The MathWorks, Inc.