%% Stack and Unstack Tables
% This example shows how to reformat a table by using stack and unstack.
%
%% Read Sample Data into a Table
% Read data from a comma-separated text file, testScores.csv, into a table by using the readtable function. testScores.csv contains test scores for several students.

T = readtable('testScores.csv')

% T is a table with 10 rows and 5 variables.
%
%% Find the Average Across Each Row
% Extract the data from the third, fourth, and fifth variables by using curly braces, {}, find the average of each row, and store it in a new variable, TestAvg.

T.TestAvg = mean(T{:,3:end},2)

% Alternatively, you can use the variable names, T{:,{'Test1','Test2','Test3'}}, or the variable indices, T{:,3:5}, to select the subset of data.
%
%% Reformat the Table
% Stack the test score variables into a new variable, Scores.

Tnew = stack(T,{'Test1','Test2','Test3'},'NewDataVariableNames','Scores')

% The original test variable names, Test1, Test2, and Test3, appear as levels in the combined test scores indicator variable, Scores_Indicator.
%
%% Revert the Table to the Original Format
% Reformat Tnew back into its original format.

Torig = unstack(Tnew,'Scores','Scores_Indicator');
Torig(:,{'LastName','Gender','Test1','Test2','Test3'})

% unstack reassigns the levels of the indicator variable, Scores_Indicator, as variable names in the unstacked table.
% Copyright 2012 The MathWorks, Inc.