www.gusucode.com > matlab 案例源码 matlab代码程序 > matlab/ApplyAggregationFunctiontoEachGroupExample.m
%% 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 table containing data on the price of two stocks over 2 days. Date = [repmat({'4/12/2008'},6,1);... repmat({'4/13/2008'},5,1)]; Stock = {'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 = table(Date,Stock,Price) %% % |S| contains two prices for |STOCK1| during the first day and four prices % for |STOCK2| during the first day. %% % Create a table containing separate variables for each stock and one row % for each day. Use |Date| 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 |'4/13/2008'| is in the seventh row % of |S|.