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

    %% Create Table from Subset of Larger Table  
% This example shows how to create a table from a subset of a larger table.   

% Copyright 2015 The MathWorks, Inc.


%% Load Sample Data 
% Load the sample patients data and create a table. Use the unique identifiers
% in |LastName| as row names. 
load patients

patients = table(Age,Gender,Height,Weight,Smoker,...
    'RowNames',LastName); 

%%
% The table, |patients|, contains 100 rows and 5 variables.  

%% 
% View the data type, description, units, and other descriptive statistics
% for each variable by using |summary| to summarize the table. 
summary(patients)  

%% Index Using Numeric Indices 
% Create a subtable containing the first five rows and all the variables
% from the table, |patients|. Use numeric indexing within the parentheses
% to specify the desired rows and variables. This is similar to indexing
% with numeric arrays. 
T1 = patients(1:5,:) 

%%
% |T1| is a 5-by-5 table. In addition to numeric indices, you can use row
% or variable names inside the parentheses. In this case, using row indices
% and a colon is more compact than using row or variable names.  

%% Index Using Names 
% Select all the data for the patients with the last names |'Adams'| and
% |'Brown'|. In this case, it is simpler to use the row names than to use
% the numeric index. 
T2 = patients({'Adams','Brown'},:) 

%%
% |T2| is a 2-by-5 table.  

%% Index Using a Logical Expression 
% Create a new table, |T3|, containing the gender, height, and weight of
% the patients under the age of 30. Select only the rows where the value
% in the variable, |Age|, is less than 30. 
%
% Use dot notation to extract data from a table variable and a logical expression
% to define the subset of rows based on that extracted data. 
rows = patients.Age<30;
vars = {'Gender','Height','Weight'}; 

%%
% |rows| is a 100-by-1 logical array containing logical |true| (|1|) for
% rows where the value in the variable, |Age|, is less than 30.  

%% 
% Use parentheses to return a table containing the desired subset of the data. 
T3 = patients(rows,vars) 

%%
% |T3| is a 15-by-3 table.