%% Apply Aggregation Function to Each Group
% Unstack data and apply an aggregation function to multiple rows in the same group that have the same values in the indicator variable.
% Create a timetable containing data on the price of two stocks over two days. To specify the row times, use datetime values. Specify the names of the stocks using a categorical array since this timetable has a fixed set of stock names.

Date = [repmat(datetime('2008-04-12'),6,1);...
        repmat(datetime('2008-04-13'),5,1)];
Stock = categorical({'Stock1';'Stock2';'Stock1';'Stock2';...
                     'Stock2';'Stock2';'Stock1';'Stock2';...
                     'Stock2';'Stock1';'Stock2'});
Price = [60.35;27.68;64.19;25.47;28.11;27.98;...
         63.85;27.55;26.43;65.73;25.94];

S = timetable(Date,Stock,Price)

% S contains two prices for Stock1 during the first day and four prices for Stock2 during the first day.
%
% Create a timetable containing separate variables for each stock and one row for each day. Use Date (the vector of row times) as the grouping variable and apply the aggregation function, @mean, to the numeric values from the variable, Price, for each group.

[U,is] = unstack(S,'Price','Stock',...
                 'AggregationFunction',@mean)

% U contains the average price for each stock grouped by date.
% is identifies the index of the first value for each group of rows in S. The first value for the group with the date April 13, 2008 is in the seventh row of S.
% Copyright 2012 The MathWorks, Inc.