Table array with named variables that can contain different types
table
arrays store column-oriented or tabular data, such as columns from a text file or spreadsheet. Tables store each piece of column-oriented data in avariable.表变量可以具有不同的数据类型d sizes as long as all variables have the same number of rows. Table variables have names, just as the fields of a structure have names. Use thesummary
function to get information about a table.
To index into a table, use smooth parentheses()
to return a subtable or curly braces{}
to extract the contents. You can access variables and rows using names. For more information on indexing using numbers and names, seeAccess Data in Tables.
You can read data from a file into a table using either theImport Tool
or thereadtable
function. Alternatively, use thetable
function described below to create a table from existing workspace variables.
You also can create a table that allows space for variables whose values are filled in later. To create a table with preallocated space for variables, use thetable
function with'Size'
as the first input argument, as described below.
T = table(
creates a table from the input variablesvar1,...,varN
)var1,...,varN
.The variables can have different sizes and data types, but all variables must have the same number of rows.
If the inputs are workspace variables, thentable
assigns their names as the variable names in the output table. Otherwise,table
assigns variable names of the form'Var1',...,'Var
, whereN
'
is the number of variables.N
T = table('Size',
creates a table and preallocates space for the variables that have data types you specify.sz
,'VariableTypes',varTypes
)sz
is a two-element numeric array, wheresz(1)
specifies the number of rows andsz(2)
specifies the number of variables.varTypes
specifies the data types of the variables.
T = table(___,
specifies additional input arguments using one or more name-value pair arguments. For example, you can specify variable names using theName,Value
)'VariableNames'
name-value pair. You can use this syntax with any of the input arguments of the previous syntaxes.
T = table
creates an empty 0-by-0 table.
var1,...,varN
—Input variablesInput variables, specified as arrays with the same number of rows. The input variables can have different sizes and different data types.
Common input variables are numeric arrays, logical arrays, character arrays, structure arrays, or cell arrays. Input variables also can be objects that are arrays. Such an array must support indexing of the formvar(index1,...,indexN)
, whereindex1
is a numeric or logical vector that corresponds to rows of the variablevar
.In addition, the array must implement both avertcat
method and asize
method with adim
argument.
Example:table([1:4]',ones(4,3,2),eye(4,2))
creates a table from variables with four rows, but different sizes.
Example:table([1:3]',{'one';'two';'three'},categorical({'A';'B';'C'}))
creates a table from variables with three rows, but different data types.
sz
—Size of preallocated tableSize of the preallocated table, specified as a two-element numeric vector. The first element ofsz
specifies the number of rows, and the second element specifies the number of table variables.
To create variables only, without any rows, specify0
as the first element ofsz
.
Example:T = table('Size',[50 3],'VariableTypes',{'string','double','datetime'})
preallocates 50 rows for a table that contains a string array, a double array, and a datetime array.
Example:T = table('Size',[0 4],'VariableTypes',varTypes)
specifies zero rows and four variables.
varTypes
—Data types of preallocated variablesData types of the preallocated variables, specified as a cell array of character vectors or a string array. The number of types specified byvarTypes
must equal the number of variables specified by the second element ofsz
.
varTypes
can contain the names of any data types, including the names shown in the table.
Data Type Name |
Initial Value in Each Element |
---|---|
|
Double- or single-precision |
|
Double- or single-precision |
|
Signed 8-, 16-, 32-, or 64-bit integer |
|
Unsigned 8-, 16-, 32-, or 64-bit integer |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Scalar structure with no fields |
|
Table with no variables |
|
Timetable with no variables and |
For any other data type, the initial value is the value used by that type or class to "in-fill" unassigned elements of an array.
If you specify'char'
as a data type, thentable
preallocates the corresponding variable as a cell array of character vectors, not as a character array. Best practice is to avoid creating table or timetable variables that are character arrays. When working with text data in a table or a timetable, consider using a string array or a categorical array.
Specify optional comma-separated pairs ofName,Value
arguments.Name
is the argument name andValue
is the corresponding value.Name
must appear inside quotes. You can specify several name and value pair arguments in any order asName1,Value1,...,NameN,ValueN
.
T = table(rowTimes,X,Y,'VariableNames',{'Latitude','Longitude'})
creates a table from input arraysX
andY
, and names the corresponding table variablesLatitude
andLongitude
.
VariableNames
—Variable namesVariable names, specified as a cell array of character vectors or a string array whose elements are nonempty and distinct.
The number of names in the array must equal the number of table variables.
Thetable
function also stores the variable names in theVariableNames
property of the table.
Variable names can have any Unicode®characters, including spaces and non-ASCII characters.
RowNames
—Row namesRow names, specified as a cell array of character vectors or a string array whose elements are nonempty and distinct.
The number of names in the array must equal the number of rows.
Thetable
function also stores the row names in theRowNames
property of the table.
Row names can have any Unicode characters, including spaces and non-ASCII characters.
Thetable
function removes any leading or trailing whitespace characters from the row names.
Example:T = table([10;20;30],{'M';'F';'F'},'VariableNames',{'Age','Gender'},'RowNames',{'P1','P2','P3'})
creates a table with both variable names and row names.
DimensionNames
—Dimension namesSince R2021a
Dimension names, specified as a two-element cell array of character vectors or two-element string array whose elements are nonempty and distinct.
Thetable
function also stores the dimension names in theDimensionNames
property of the table.
Dimension names can have any Unicode characters, including spaces and non-ASCII characters.
Before R2021a, you can specify dimension names only by setting theDimensionNames
property.
Access Table Metadata Properties
A table contains metadata properties that describe the table and its variables. Access these properties using the syntax
, wheretableName
.改过的ies.改过的yName
is the name of a property. For example, you can access the names of the variables in table改过的yName
T
using the syntaxT.Properties.VariableNames
.
You can return a summary of all the metadata properties using the syntax
.tableName
.改过的ies
Tables provide metadata access through the改过的ies
property because you can access table data directly using dot syntax. For example, if tableT
has a variable namedVar1
, then you can access the values in the variable by using the syntaxT.Var1
.
DimensionNames
—Dimension names{'Row','Variables'}
(default) |two-element cell array of character vectors|two-element string arrayDimension names, specified as a two-element cell array of character vectors or a two-element string array.
Dimension names can have any Unicode characters, including spaces and non-ASCII characters.
If you specify this property using a string array, then it is converted and stored as a cell array of character vectors.
You can access table data using the two dimension names.
If the table has row names, and you use dot syntax and the first dimension name, then you can access the row names as a vector.
If you use dot syntax and the second dimension name, then the data from all the variables are concatenated together in one array, as though you had indexed into the table using{:,:}
syntax.
Create a table and display its dimension names. You can access row names and data using dimension names with dot syntax.
loadpatientsT = table(Age,Height,Weight,Systolic,Diastolic,...'RowNames',LastName); T.Properties.DimensionNames
ans =1x2 cell{'Row'} {'Variables'}
Access the row names using the first dimension name. Display the first five names.
T.Row(1:5)
ans =5x1 cell{'Smith' } {'Johnson' } {'Williams'} {'Jones' } {'Brown' }
Access the data using the second dimension name. This syntax is equivalent toT{:,:}
.
T.Variables
ans =100×538 71 176 124 93 43 69 163 109 77 38 64 131 125 83 40 67 133 117 75 49 64 119 122 80 46 68 142 121 70 33 64 142 130 88 40 68 180 115 82 28 68 183 115 78 31 66 132 118 86 ⋮
Modify the names of its dimensions using the改过的ies.DimensionNames
property. Having changed the dimension names, you can access the row names and data using the syntaxesT.Patient
andT.Data
respectively.
T.Properties.DimensionNames = {'Patient','Data'}; T.Properties
ans = TableProperties属性:描述: '' UserData: [] DimensionNames: {'Patient' 'Data'} VariableNames: {'Age' 'Height' 'Weight' 'Systolic' 'Diastolic'} VariableDescriptions: {} VariableUnits: {} VariableContinuity: [] RowNames: {100x1 cell} CustomProperties: No custom properties are set. Use addprop and rmprop to modify CustomProperties.
RowNames
—Row names{}
(default) |单元阵列的特征向量|string arrayRow names, specified as a cell array of character vectors or a string array whose elements are nonempty and distinct. IfRowNames
is not empty, then the number of row names must equal the number of rows in the table.
Row names can have any Unicode characters, including spaces and non-ASCII characters.
If you assign row names with leading or trailing whitespace characters, then MATLAB®removes them from the row names.
The row names are visible when you view the table. Furthermore, you can use the row names within parentheses or curly braces to access the table data.
Another way to access the row names is to use dot syntax and the name of the first dimension of the table.
If you specify this property using a string array, then it is converted and stored as a cell array of character vectors.
Create a table. Then add row names and access rows by their names.
loadpatientsT =表(性别、年龄、身高、体重、吸烟,收缩压,Diastolic);
Add row names using the改过的ies.RowNames
property. By default, tables do not have row names, but you can add them at any time.
T.Properties.RowNames = LastName; head(T,4)
ans=4×7 tableGender Age Height Weight Smoker Systolic Diastolic __________ ___ ______ ______ ______ ________ _________ Smith {'Male' } 38 71 176 true 124 93 Johnson {'Male' } 43 69 163 false 109 77 Williams {'Female'} 38 64 131 false 125 83 Jones {'Female'} 40 67 133 false 117 75
Another way to access the row names is by using dot syntax with the name of the first dimension of the table. Display the first five row names.
T.Properties.DimensionNames
ans =1x2 cell{'Row'} {'Variables'}
T.Row(1:5)
ans =5x1 cell{'Smith' } {'Johnson' } {'Williams'} {'Jones' } {'Brown' }
索引the table by row names.
T({'Smith','Williams'},:)
ans=2×7 tableGender Age Height Weight Smoker Systolic Diastolic __________ ___ ______ ______ ______ ________ _________ Smith {'Male' } 38 71 176 true 124 93 Williams {'Female'} 38 64 131 false 125 83
Description
—Table description''
(default) |character vector|string scalarTable description, specified as a character vector or string scalar. This description is visible when using thesummary
function.
If you specify this property using a string scalar, then it is converted and stored as a character vector.
Create a table. Modify the description of the table. Display a summary of the result.
loadpatientsT = table(Gender,Age,Height,Weight); T.Properties.Description ='Simulated patient data'; summary(T)
Description: Simulated patient data Variables: Gender: 100x1 cell array of character vectors Age: 100x1 double Values: Min 25 Median 39 Max 50 Height: 100x1 double Values: Min 60 Median 67 Max 72 Weight: 100x1 double Values: Min 111 Median 142.5 Max 202
UserData
—Additional table information[]
(default) |arrayAdditional table information, specified as an array. You can attach data of any kind to a table using this property.
Create a table. Attach an anonymous function as a piece of user data that is associated with the table.
loadpatientsT =表(性别、年龄、身高、体重、吸烟,收缩压,Diastolic); formula = @(x) x.^2; T.Properties.UserData = formula; T.Properties
ans = TableProperties属性:描述: '' UserData: @(x)x.^2 DimensionNames: {'Row' 'Variables'} VariableNames: {1x7 cell} VariableDescriptions: {} VariableUnits: {} VariableContinuity: [] RowNames: {} CustomProperties: No custom properties are set. Use addprop and rmprop to modify CustomProperties.
VariableNames
—Variable namesVariable names, specified as a cell array of character vectors or a string array whose elements are nonempty and distinct. The number of names must equal the number of variables.
Variable names can have any Unicode characters, including spaces and non-ASCII characters.
The variable names are visible when viewing the table and when using thesummary
function. Furthermore, you can use the variable names within parentheses, within curly braces, or with dot indexing to access table data.
If you specify this property using a string array, then it is converted and stored as a cell array of character vectors.
Create a table with default variable names. Then modify the names using the改过的ies.VariableNames
property.
T = table({'M';'M';'F';'F';'F'},[38, 43岁,38;40;49),...[71;69;64;67;64],[176;163;131;133;119])
T=5×4 tableVar1 Var2 Var3 Var4 _____ ____ ____ ____ {'M'} 38 71 176 {'M'} 43 69 163 {'F'} 38 64 131 {'F'} 40 67 133 {'F'} 49 64 119
T.Properties.VariableNames = {'Gender','Age','Height','Weight'}
T=5×4 tableGender Age Height Weight ______ ___ ______ ______ {'M'} 38 71 176 {'M'} 43 69 163 {'F'} 38 64 131 {'F'} 40 67 133 {'F'} 49 64 119
A fundamental way to display and modify variables is to access them by name using dot syntax.
T.Age
ans =5×138 43 38 40 49
T.Age(1) = 53
T=5×4 tableGender Age Height Weight ______ ___ ______ ______ {'M'} 53 71 176 {'M'} 43 69 163 {'F'} 38 64 131 {'F'} 40 67 133 {'F'} 49 64 119
VariableDescriptions
—Variable descriptions{}
(default) |单元阵列的特征向量|string arrayVariable descriptions, specified as a cell array of character vectors or a string array This property can be an empty cell array, which is the default. If the array is not empty, then it must contain as many elements as there are variables. You can specify an individual empty character vector or empty string for a variable that does not have a description.
The variable descriptions are visible when using thesummary
function.
If you specify this property using a string array, then it is converted and stored as a cell array of character vectors.
Create a table. Modify the variable descriptions. Display a summary of the result.
loadpatientsT =表(性别、年龄、身高、体重、吸烟,收缩压,Diastolic); T.Properties.VariableDescriptions = {'','','','',...'Has the patient ever been a smoker',...'Systolic Pressure','Diastolic Pressure'}; summary(T)
Variables: Gender: 100x1 cell array of character vectors Age: 100x1 double Values: Min 25 Median 39 Max 50 Height: 100x1 double Values: Min 60 Median 67 Max 72 Weight: 100x1 double Values: Min 111 Median 142.5 Max 202 Smoker: 100x1 logical Properties: Description: Has the patient ever been a smoker Values: True 34 False 66 Systolic: 100x1 double Properties: Description: Systolic Pressure Values: Min 109 Median 122 Max 138 Diastolic: 100x1 double Properties: Description: Diastolic Pressure Values: Min 68 Median 81.5 Max 99
VariableUnits
—Variable units{}
(default) |单元阵列的特征向量|string arrayVariable units, specified as a cell array of character vectors or a string array. This property can be an empty cell array, which is the default. If the array is not empty, then it must contain as many elements as there are variables. You can specify an individual empty character vector or empty string for a variable that does not have units.
The variable units are visible when using thesummary
function.
If you specify this property using a string array, then it is converted and stored as a cell array of character vectors.
Create a table. Modify the variable units. Display a summary of the result.
loadpatientsT =表(性别、年龄、身高、体重、吸烟,收缩压,Diastolic); T.Properties.VariableUnits = {'',“年”,'In','Lbs','','mm Hg','mm Hg'}; summary(T)
Variables: Gender: 100x1 cell array of character vectors Age: 100x1 double Properties: Units: Yrs Values: Min 25 Median 39 Max 50 Height: 100x1 double Properties: Units: In Values: Min 60 Median 67 Max 72 Weight: 100x1 double Properties: Units: Lbs Values: Min 111 Median 142.5 Max 202 Smoker: 100x1 logical Values: True 34 False 66 Systolic: 100x1 double Properties: Units: mm Hg Values: Min 109 Median 122 Max 138 Diastolic: 100x1 double Properties: Units: mm Hg Values: Min 68 Median 81.5 Max 99
VariableContinuity
—Status as continuous or discrete variables[]
(default) |单元阵列的特征向量|string arrayStatus as continuous or discrete variables, specified as a cell array of character vectors or a string array.
While tables and timetables both have this property, only timetables use it. For more information, see theVariableContinuity
property oftimetable
.
CustomProperties
—Customized metadata of table and its variablesCustomProperties
objectCustomized metadata of a table and its variables, specified as aCustomProperties
object.
TheCustomProperties
object is a container for customized metadata that you can add to a table. By default,CustomProperties
has zero properties. Each property you add toCustomProperties
can contain either table metadata or variable metadata. If a property contains variable metadata, then its value must be an array, and the number of elements in the array must equal the number of table variables.
To add properties for customized metadata to a table, use theaddprop
function.
To access or modify customized metadata, use the syntax
.In this syntax,tableName
.改过的ies.CustomProperties.改过的yName
is the name you chose when you added that property using改过的yName
addprop
.
To remove properties, use thermprop
function.
Note:You can add or removeonlyproperties for customized metadata usingaddprop
andrmprop
.You cannot add or remove properties of the
object.tableName
.改过的ies
Create a table.
loadpatientsT =表(性别、年龄、身高、体重、吸烟,收缩压,Diastolic);
Add properties that can hold customized metadata about the table and its variables. In this example, the metadata are names of instruments,true
andfalse
values indicating whether variables are to be plotted, and the name of an output file. To add properties, use theaddprop
function.
T = addprop(T,{'Instrument','ToPlot','OutputFile'},{'variable','variable','table'}); T.Properties
ans = TableProperties属性:描述: '' UserData: [] DimensionNames: {'Row' 'Variables'} VariableNames: {1x7 cell} VariableDescriptions: {} VariableUnits: {} VariableContinuity: [] RowNames: {} Custom Properties (access using t.Properties.CustomProperties.): OutputFile: [] Instrument: [] ToPlot: []
Assign values to the customized metadata using dot syntax. When you assign an array of text values to customized metadata, the best practice is to use a string array, not a cell array of character vectors. If a property ofCustomProperties
is a cell array of character vectors, then there is no mechanism to prevent you from later assigning nontext values as elements of the cell array.
T.Properties.CustomProperties.Instrument = ["","","height rod","scale","","blood pressure cuff","blood pressure cuff"]; T.Properties.CustomProperties.ToPlot = [false false true true false true true]; T.Properties.CustomProperties.OutputFile ='patientData.csv'; T.Properties
ans = TableProperties属性:描述: '' UserData: [] DimensionNames: {'Row' 'Variables'} VariableNames: {1x7 cell} VariableDescriptions: {} VariableUnits: {} VariableContinuity: [] RowNames: {} Custom Properties (access using t.Properties.CustomProperties.): OutputFile: 'patientData.csv' Instrument: ["" "" "height rod" "scale" ... ] ToPlot: [0 0 1 1 0 1 1]
Remove theOutputFile
property fromT
.
T = rmprop(T,'OutputFile'); T.Properties
ans = TableProperties属性:描述: '' UserData: [] DimensionNames: {'Row' 'Variables'} VariableNames: {1x7 cell} VariableDescriptions: {} VariableUnits: {} VariableContinuity: [] RowNames: {} Custom Properties (access using t.Properties.CustomProperties.): Instrument: ["" "" "height rod" "scale" ... ] ToPlot: [0 0 1 1 0 1 1]
Store data about a group of patients in a table. You can perform calculations and store results in the same table. Also, you can annotate the table to describe your work and the variables of the table.
First, create workspace variables that have the patient data. The variables can have any data types but must have the same number of rows.
LastName = {'Sanchez';'Johnson';'Li';'Diaz';'Brown'}; Age = [38;43;38;40;49]; Smoker = logical([1;0;1;0;1]); Height = [71;69;64;67;64]; Weight = [176;163;131;133;119]; BloodPressure = [124 93; 109 77; 125 83; 117 75; 122 80];
Create a table,T
, as a container for the workspace variables. Thetable
function uses the workspace variable names as the names of the table variables inT
.A table variable can have multiple columns. For example, theBloodPressure
variable in T is a 5-by-2 array.
T = table(LastName,Age,Smoker,Height,Weight,BloodPressure)
T=5×6 tableLastName Age Smoker Height Weight BloodPressure ___________ ___ ______ ______ ______ _____________ {'Sanchez'} 38 true 71 176 124 93 {'Johnson'} 43 false 69 163 109 77 {'Li' } 38 true 64 131 125 83 {'Diaz' } 40 false 67 133 117 75 {'Brown' } 49 true 64 119 122 80
You can use dot indexing to access table variables. For example, calculate the mean height of the patients using the values inT.Height
.
meanHeight = mean(T.Height)
meanHeight = 67
Calculate body mass index (BMI), and add it as a new table variable. You also can add and name table variables in one step, using dot syntax.
T.BMI = (T.Weight*0.453592)./(T.Height*0.0254).^2
T=5×7 tableLastName Age Smoker Height Weight BloodPressure BMI ___________ ___ ______ ______ ______ _____________ ______ {'Sanchez'} 38 true 71 176 124 93 24.547 {'Johnson'} 43 false 69 163 109 77 24.071 {'Li' } 38 true 64 131 125 83 22.486 {'Diaz' } 40 false 67 133 117 75 20.831 {'Brown' } 49 true 64 119 122 80 20.426
Annotate the table with a description of the BMI calculation. You can annotateT
and its variables using metadata accessed throughT.Properties
.
T.Properties.Description ='Patient data, including body mass index (BMI) calculated using Height and Weight'; T.Properties
ans = TableProperties属性:描述: 'Patient data, including body mass index (BMI) calculated using Height and Weight' UserData: [] DimensionNames: {'Row' 'Variables'} VariableNames: {1x7 cell} VariableDescriptions: {} VariableUnits: {} VariableContinuity: [] RowNames: {} CustomProperties: No custom properties are set. Use addprop and rmprop to modify CustomProperties.
Access all the data from a table as a matrix, using the name of the second dimension of the table.
Create a table that has five rows of data about a set of patients.
Age = [38;43;38;40;49]; Smoker = logical([1;0;1;0;1]); Height = [71;69;64;67;64]; Weight = [176;163;131;133;119]; BloodPressure = [124 93; 109 77; 125 83; 117 75; 122 80]; T = table(Age,Smoker,Height,Weight,BloodPressure)
T=5×5 tableAge Smoker Height Weight BloodPressure ___ ______ ______ ______ _____________ 38 true 71 176 124 93 43 false 69 163 109 77 38 true 64 131 125 83 40 false 67 133 117 75 49 true 64 119 122 80
Display the names of the table dimensions using theDimensionNames
property. The default name of the second dimension isVariables
.
T.Properties.DimensionNames
ans =1x2 cell{'Row'} {'Variables'}
Access the table data as a matrix using the syntaxT.Variables
.This syntax is equivalent to accessing all the contents using curly brace syntax,T{:,:}
.If the table data cannot be concatenated into a matrix, then an error message is raised.
T.Variables
ans =5×638 1 71 176 124 93 43 0 69 163 109 77 38 1 64 131 125 83 40 0 67 133 117 75 49 1 64 119 122 80
Rename the second dimension. If you change the name, then you can use the new name to access the data.
T.Properties.DimensionNames{2} ='PatientData'; T.PatientData
ans =5×638 1 71 176 124 93 43 0 69 163 109 77 38 1 64 131 125 83 40 0 67 133 117 75 49 1 64 119 122 80
Preallocate a table by specifying its size and the data types of the variables. Thetable
function fills the variables with default values that are appropriate for the data types you specify. It also gives the variables default names, but you also can assign variable names of your own. Preallocation provides room for data you add to the table later.
sz = [4 3]; varTypes = {'double','datetime','string'}; T = table('Size',sz,'VariableTypes',varTypes)
T=4×3 tableVar1 Var2 Var3 ____ ____ _________ 0 NaT0 NaT 0 NaT 0 NaT
To specify names for the variables, use the'VariableNames'
name-value pair argument.
varNames = {'Temperature','Time','Station'}; T2 = table('Size',sz,'VariableTypes',varTypes,'VariableNames',varNames)
T2=4×3 tableTemperature Time Station ___________ ____ _________ 0 NaT0 NaT 0 NaT 0 NaT
Add rows of data to the first two rows ofT2
.Preallocation can be a useful technique when your code adds one row of data, or a few rows of data, at a time. Instead of growing the table every time you add a row, you can fill in table variables that already have room for your data.
T2(1,:) = {75,datetime('now'),"S1"}; T2(2,:) = {68,datetime('now')+1,"S2"}
T2=4×3 tableTemperature Time Station ___________ ____________________ _________ 75 01-Sep-2021 09:50:40 "S1" 68 02-Sep-2021 09:50:40 "S2" 0 NaT0 NaT
You can encapsulate a row of data values in a cell array. When you assign a row from a cell array, elements from the cell array are assigned to the row in the table.
Create a table from arrays. To specify table variable names, use the'VariableNames'
name-value pair argument. For example, you can use'VariableNames'
to specify names when the other input arguments are not workspace variables.
T = table(categorical({'M';'F';'M'}),[45;32;34],...{'NY';'CA';'MA'},logical([1;0;0]),...'VariableNames',{'Gender','Age','State','Vote'})
T=3×4 tableGender Age State Vote ______ ___ ______ _____ M 45 {'NY'} true F 32 {'CA'} false M 34 {'MA'} false
Create a table with the state names as row names. You can specify both the'VariableNames'
and'RowNames'
name-value pairs when using thetable
function.
T = table(categorical({'M';'F';'M'}),[45;32;34],logical([1;0;0]),...'VariableNames',{'Gender','Age','Vote'},...'RowNames',{'NY';'CA';'MA'})
T=3×3 tableGender Age Vote ______ ___ _____ NY M 45 true CA F 32 false MA M 34 false
Specify row names for a table. Tables do not have to have row names, but if you specify them, then you can index into a table by row name. You also can access the set of row names using the name of the first dimension of a table.
Create arrays containing patient data.
LastName = {'Sanchez';'Johnson';'Lee';'Diaz';'Brown'}; Age = [38;43;38;40;49]; Height = [71;69;64;67;64]; Weight = [176;163;131;133;119];
Create a table containing the arrays. SpecifyLastName
as the source of row names for the table. The table has only three variables. The row names are not a table variable, but instead a property of the table.
T = table(Age,Weight,Height,'RowNames',LastName)
T=5×3 tableAge Weight Height ___ ______ ______ Sanchez 38 176 71 Johnson 43 163 69 Lee 38 131 64 Diaz 40 133 67 Brown 49 119 64
Since the rows have row names, you can index into the rows ofT
by name.
T('Lee',:)
ans=1×3 tableAge Weight Height ___ ______ ______ Lee 38 131 64
To specify multiple rows, use a cell array.
T({'Lee','Brown'},:)
ans=2×3 tableAge Weight Height ___ ______ ______ Lee 38 131 64 Brown 49 119 64
To access all the row names ofT
as a cell array, use the syntaxT.Row
.By default,Row
is the name of the first dimension of a table.
T.Row
ans =5x1 cell{'Sanchez'} {'Johnson'} {'Lee' } {'Diaz' } {'Brown' }
Change the name of the first dimension. If you change the name, then you can access the row names using the new name.
T.Properties.DimensionNames{1} ='LastNames'; T.LastNames
ans =5x1 cell{'Sanchez'} {'Johnson'} {'Lee' } {'Diaz' } {'Brown' }
Starting in R2017a, you can create strings using double quotes, and add string arrays as table variables.
FlightNum = [1261;547;3489]; Customer = ["Jones";"Brown";"Smith"]; Date = datetime(2016,12,20:22)'; Rating = categorical(["Good";"Poor";"Fair"]); Comment = ["Flight left on time, not crowded";..."Late departure, ran out of dinner options";..."Late, but only by half an hour. Otherwise fine."]; T = table(FlightNum,Customer,Date,Rating,Comment)
T=3×5 tableFlightNum Customer Date Rating Comment _________ ________ ___________ ______ _________________________________________________ 1261 "Jones" 20-Dec-2016 Good "Flight left on time, not crowded" 547 "Brown" 21-Dec-2016 Poor "Late departure, ran out of dinner options" 3489 "Smith" 22-Dec-2016 Fair "Late, but only by half an hour. Otherwise fine."
To use the text in a string array as row names, convert the string array to a cell array of character vectors. Then create a table with row names.
Customer = cellstr(Customer); T = table(FlightNum,Date,Rating,Comment,'RowNames',Customer)
T=3×4 tableFlightNum Date Rating Comment _________ ___________ ______ _________________________________________________ Jones 1261 20-Dec-2016 Good "Flight left on time, not crowded" Brown 547 21-Dec-2016 Poor "Late departure, ran out of dinner options" Smith 3489 22-Dec-2016 Fair "Late, but only by half an hour. Otherwise fine."
Create workspace variables containing snowfall totals on different dates at three locations. These variables are row vectors.
Date = {'12/25/11','1/2/12','1/23/12','2/7/12','2/15/12'}; location1 = [20 5 13 0 17]; location2 = [18 9 21 5 12]; location3 = [26 10 16 3 15];
One way to create a table from these variables is to call thetable
function with the syntaxT = table(Date',location1',location2',location3')
.Because the workspace variables are row vectors, you must transpose them to put them into the table as column-oriented data. Therefore, the input arguments are expressions, not simple variables. As a result,table
createsT
with the default variable namesVar1
,Var2
,Var3
, andVar4
.You can assign more meaningful names toT.Properties.VariableNames
after you createT
.But, it might be more convenient to create an empty table, and then add variables one at a time with new names.
Create an empty table. Transpose the workspace variables and add them to the table as column vectors. As part of assigning each workspace variable intoT
, provide a meaningful name for the table variable.
T = table; T.Date = Date'; T.Natick = location1'; T.Boston = location2'; T.Worcester = location3'
T=5×4 tableDate Natick Boston Worcester ____________ ______ ______ _________ {'12/25/11'} 20 18 26 {'1/2/12' } 5 9 10 {'1/23/12' } 13 21 16 {'2/7/12' } 0 5 3 {'2/15/12' } 17 12 15
Starting in R2019b, you can specify table variable names that are not valid MATLAB® identifiers. Such variable names can include spaces, non-ASCII characters, and can have any character as the leading character. When you access such a variable name, enclose it quotation marks.
创建一个表存储s data about a set of patients. Start with their ages and status as smokers.
Age = [38;43;38;40;49]; Smoker = logical([1;0;1;0;1]); Height = [71;69;64;67;64]; Weight = [176;163;131;133;119]; BloodPressure = [124 93; 109 77; 125 83; 117 75; 122 80]; T = table(Age,Smoker)
T=5×2 tableAge Smoker ___ ______ 38 true 43 false 38 true 40 false 49 true
Add the blood pressure readings with the variable name'29-May-2019 Blood Pressure Reading'
.You can use dot syntax to add or access the variable. Since its name is not a valid MATLAB identifier, use parentheses and quotation marks with dot syntax.
T.('29-May-2019 Blood Pressure Reading') = BloodPressure
T=5×3 table吸烟者年龄29日——2019年5月,血压阅读_________ __________________________________ 38 true 124 93 43 false 109 77 38 true 125 83 40 false 117 75 49 true 122 80
When table variable names are valid MATLAB identifiers, you can use dot syntax without parentheses and quotation marks.
T.Height = Height; T.Weight = Weight
T=5×5 tableAge Smoker 29-May-2019 Blood Pressure Reading Height Weight ___ ______ __________________________________ ______ ______ 38 true 124 93 71 176 43 false 109 77 69 163 38 true 125 83 64 131 40 false 117 75 67 133 49 true 122 80 64 119
索引T
using variable names.
T (:, {'Age','Smoker','29-May-2019 Blood Pressure Reading'})
ans=5×3 table吸烟者年龄29日——2019年5月,血压阅读_________ __________________________________ 38 true 124 93 43 false 109 77 38 true 125 83 40 false 117 75 49 true 122 80
Use single quotes for these input names:
'DimensionNames'
(since R2021a)
'RowNames'
'Size'
'VariableTypes'
'VariableNames'
To avoid confusion with variable inputs, do not use double-quoted string scalars (such as"RowNames"
) for these names.
For a list of functions that accept or return tables, seeTables.
Behavior changed in R2019b
Table and timetable variable names with leading or trailing whitespace characters are not modified.
In previous releases, leading and trailing whitespace characters were deleted from variable names when you specified them using the'VariableNames'
name-value pair argument, or assigned them to theVariableNames
property.
To manually remove such characters, first use thestrtrim
function on the names, then assign them as variable names to the table or timetable.
Behavior changed in R2019b
MATLAB raises an error if you assign a table variable name that matches a dimension name, or a dimension name that matches a variable name. In previous releases, MATLAB raised a warning and modified the names so they were unique.
Behavior changed in R2021a
MATLAB raises an error if you assign a dimension name that matches one of these reserved names:'Properties'
,'RowNames'
,'VariableNames'
, or':'
.In previous releases, MATLAB raised a warning and modified the dimension names so that they were different from the reserved names.
This function supports tall arrays with the limitation:
The syntaxTT = table(T1,T2,...)
constructs a tall table from several tall arrays(T1,T2,...)
.You can use the'VariableNames'
name-value pair argument to specify variable names.
For more information, seeTall Arrays for Out-of-Memory Data.
Usage notes and limitations:
Starting in R2019b, you can use tables in MATLAB code intended for code generation. For more information, seeCode Generation for Tables(MATLAB Coder)andTable Limitations for Code Generation(MATLAB Coder).
Usage notes and limitations:
The input arrays must be distributed and have the same number of rows.
The result is distributed, using a 1D distribution scheme over the first dimension.
For more information, seeRun MATLAB Functions with Distributed Arrays(Parallel Computing Toolbox).
Tiene una versión modificada de este ejemplo. ¿Desea abrir este ejemplo con sus modificaciones?
Ha hecho clic en un enlace que corresponde a este comando de MATLAB:
Ejecute el comando introduciéndolo en la ventana de comandos de MATLAB. Los navegadores web no admiten comandos de MATLAB.
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select:.
Selectweb siteYou can also select a web site from the following list:
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.