www.gusucode.com > matlab 案例源码 matlab代码程序 > matlab/StackVariablesandSpecifyVariableNamesExample.m

    %% Stack Variables and Specify Variable Names  

%% 
% Create a table indicating the amount of snowfall at three locations from
% five separate storms. 
Storm = [1;2;3;4;5];
Date = {'12/25/11';'1/2/12';'1/23/12';'2/7/12';'2/15/12'};
Natick = [20;5;13;0;17];
Boston = [18;9;21;5;12];
Worcester = [26;10;16;3;15];

U = table(Storm,Date,Natick,Boston,Worcester) 

%%
% The variables |Storm| and |Date| contain data that is constant at each
% location.  

%% 
% Stack the variables |Natick|, |Boston|, and |Worcester| into a single
% variable. Name the variable containing the stacked data, |Snowfall|, and
% name the new indicator variable, |Town|. 
S = stack(U,{'Natick','Boston','Worcester'},...
    'NewDataVariableName','Snowfall',...
    'IndexVariableName','Town') 

%%
% |S| contains three rows for each storm, and |stack| repeats the data in
% the constant variables, |Storm| and |Date|, accordingly. 

%%
% The categorical variable, |Town|, identifies which variable in |U| contains
% the corresponding |Snowfall| data.