目录
readtable是基于文件创建表。
语法
T = readtable(filename)
T = readtable(filename,opts)
T = readtable(___,Name,Value)
说明
T= readtable(filename) 通过从文件中读取列向数据来创建表。
readtable 基于文件的扩展名确定文件格式:
-
.txt、.dat 或 .csv(适用于带分隔符的文本文件)
-
.xls、.xlsb、.xlsm、.xlsx、.xltm、.xltx 或 .ods(适用于电子表格文件)
readtable 为该文件中的每列在 T 中创建一个变量并从文件的第一行中读取变量名称。默认情况下,readtable 会根据在输入文件的每列中检测到的数据值来创建具有适当数据类型的变量。
T = readtable(filename,opts) 使用导入选项 opts 创建表。
T = readtable(___,Name,Value) 基于文件创建一个表,并通过一个或多个名称-值对组参数指定其他选项。例如,可以指定 readtable 是将文件的第一行读取为变量名称还是数据。
要为数据设置特定的导入选项,可以使用 opts 对象,也可以指定名称-值对组。当指定除 opts 之外的名称-值对组时,readtable 仅支持下列名称-值对组:
-
文本和电子表格参数 - ReadVariableNames、ReadRowNames
-
仅文本参数 - DateLocale、Encoding
-
仅电子表格参数 - Sheet、UseExcel
示例
基于文本文件创建表
加载文件 myCsvTable.dat 并在文本编辑器中预览其内容。屏幕截图如下所示。请注意,该文件包含逗号分隔的列向数据。
filename = 'myCsvTable.dat';
基于逗号分隔的文本文件创建表。生成的表 T 为文件中的每一列包含一个变量,readtable 将文件第一行中的项视为变量名称。
T = readtable(filename)
T=5×6 table
LastName Gender Age Height Weight Smoker
____________ ______ ___ ______ ______ ______
{'Smith' } {'M'} 38 71 176 1
{'Johnson' } {'M'} 43 69 163 0
{'Williams'} {'F'} 38 64 131 0
{'Jones' } {'F'} 40 67 133 0
{'Brown' } {'F'} 49 64 119 0
忽略标题并填充缺失值
从 R2020a 开始,readtable函数读取输入文件的方式就好像它自动对该文件调用 detectImportOptions 函数一样。它可以检测数据类型,丢弃多余的标题行,并填充缺失值。
例如,在文本编辑器中预览文件 headersAndMissing.txt。该文件有一个列名行,还有一个标题行。最后两行有空缺,前面的各行包含数据值。
基于该文件创建一个表。readtable 函数将丢弃标题。此外,它还用适当的缺失值来填补空缺 - 对于数值变量,用 NaN 值;对于文本,用空字符向量。
T = readtable('headersAndMissing.txt')
T=5×6 table
LastName Gender Age Height Weight Smoker
___________ __________ ___ ______ ______ ______
{'Wu' } {'M' } 38 71 176 1
{'Johnson'} {'M' } 43 69 163 0
{'Sanchez'} {'F' } 38 64 131 0
{'Brown' } {'F' } NaN 67 133 0
{'Picard' } {0x0 char} NaN 64 119 0
要还原以前的版本的默认行为,请指定 'Format','auto' 名称-值对组参数。readtable 会将标题作为数据读取,因此,它会将所有表变量均转换为文本。
T = readtable('headersAndMissing.txt','Format','auto')
T=6×6 table
LastName Gender Age Height Weight Smoker
___________ __________ __________ _______ _______ ___________
{'string' } {'string'} {'int' } {'int'} {'int'} {'boolean'}
{'Wu' } {'M' } {'38' } {'71' } {'176'} {'1' }
{'Johnson'} {'M' } {'43' } {'69' } {'163'} {'0' }
{'Sanchez'} {'F' } {'38' } {'64' } {'131'} {'0' }
{'Brown' } {'F' } {0x0 char} {'67' } {'133'} {'0' }
{'Picard' } {0x0 char} {0x0 char} {'64' } {'119'} {'0' }
有关详细信息,请参阅本页的“兼容性注意事项”部分。
基于文本文件创建表,无列标题
在文本编辑器中预览文件 mySpaceDelimTable.txt。屏幕截图如下所示。请注意,该文件包含空格分隔的列向数据。
基于以空格分隔的文本文件创建一个表。由于文件的第一行不包含可检测到的列名称,因此 readtable 函数将分配默认的变量名称 Var1 到 Var5。
T = readtable('mySpaceDelimTable.txt')
T=3×5 table
Var1 Var2 Var3 Var4 Var5
_____ ____ ____ ______ _________
{'M'} 45 45 {'NY'} {'true' }
{'F'} 41 32 {'CA'} {'false'}
{'M'} 40 34 {'MA'} {'false'}
基于文本文件创建格式表
加载文件 myCsvTable.dat 并在文本编辑器中预览其内容。屏幕截图如下所示。请注意,该文件包含逗号分隔的列向数据。
filename = 'myCsvTable.dat';
基于逗号分隔的文本文件创建表。将前两列导入为字符向量,将第三列导入为 uint32,将接下来的两列导入为双精度浮点数。将最后一列的条目导入为字符向量。
T = readtable(filename,'Format','%s%s%u%f%f%s')
T=5×6 table
LastName Gender Age Height Weight Smoker
____________ ______ ___ ______ ______ ______
{'Smith' } {'M'} 38 71 176 {'1'}
{'Johnson' } {'M'} 43 69 163 {'0'}
{'Williams'} {'F'} 38 64 131 {'0'}
{'Jones' } {'F'} 40 67 133 {'0'}
{'Brown' } {'F'} 49 64 119 {'0'}
对于字符向量元胞数组,转换设定符为 %s,对于 double,转换设定符为 %f,对于 uint32,转换设定符为 %u。
从文本文件读取外语日期
从文件读取以德语表示的日期,再用以英语表示的日期形式,将其添加到一个表中。
在文本编辑器中预览文件 german_dates.txt。屏幕截图如下所示。请注意,第一列值包含德语的日期,第二列和第三列是数值。
使用 readtable 读取示例文件。对于日期,转换设定符为 %D,对于浮点值,转换设定符为 %f。使用 FileEncoding 名称-值对组参数指定文件编码。使用 DateLocale 名称-值对组参数指定日期格式和区域设置。
T = readtable('german_dates.txt',...
'Format','%{dd MMMM yyyy}D %f %f',...
'FileEncoding','ISO-8859-15',...
'DateLocale','de_DE')
T=3×3 table
Var1 Var2 Var3
________________ ____ _____
01 January 2014 20.2 100.5
01 February 2014 21.6 102.7
01 March 2014 20.7 99.8
基于包含行名称的电子表格创建表
基于包含第一行的变量名称和第一列的行名称的电子表格创建表。
T = readtable('patients.xls','ReadRowNames',true);
显示表的前五行和前四个变量。
T(1:5,1:4)
ans=5×4 table
Gender Age Location Height
__________ ___ _____________________________ ______
Smith {'Male' } 38 {'County General Hospital' } 71
Johnson {'Male' } 43 {'VA Hospital' } 69
Williams {'Female'} 38 {'St. Mary's Medical Center'} 64
Jones {'Female'} 40 {'VA Hospital' } 67
Brown {'Female'} 49 {'County General Hospital' } 64
查看该表的 DimensionNames 属性。
T.Properties.DimensionNames
ans = 1x2 cell
{'LastName'} {'Variables'}
'LastName' 是电子表格第一行第一列中的名称。
从电子表格中读取特定范围的数据
使用电子表格 patients.xls 的指定区域中的数据创建表。使用 C2 和 E6 两个对角之间的 5×3 矩形区域内的数据。不要将该区域的第一行用作变量名称。
T = readtable('patients.xls',...
'Range','C2:E6',...
'ReadVariableNames',false)
T =
Var1 Var2 Var3
____ ___________________________ ____
38 'County General Hospital' 71
43 'VA Hospital' 69
38 'St. Mary's Medical Center' 64
40 'VA Hospital' 67
49 'County General Hospital' 64
T 包含默认的变量名称。
检测并使用针对文本文件的导入选项
创建导入选项,定制多个变量的数据类型,然后读取数据。根据文本文件创建导入选项对象。
opts = detectImportOptions('airlinesmall.csv')
opts =
DelimitedTextImportOptions with properties:
Format Properties:
Delimiter: {','}
Whitespace: '\b\t '
LineEnding: {'\n' '\r' '\r\n'}
CommentStyle: {}
ConsecutiveDelimitersRule: 'split'
LeadingDelimitersRule: 'keep'
TrailingDelimitersRule: 'ignore'
EmptyLineRule: 'skip'
Encoding: 'ISO-8859-1'
Replacement Properties:
MissingRule: 'fill'
ImportErrorRule: 'fill'
ExtraColumnsRule: 'addvars'
Variable Import Properties: Set types by name using setvartype
VariableNames: {'Year', 'Month', 'DayofMonth' ... and 26 more}
VariableTypes: {'double', 'double', 'double' ... and 26 more}
SelectedVariableNames: {'Year', 'Month', 'DayofMonth' ... and 26 more}
VariableOptions: Show all 29 VariableOptions
Access VariableOptions sub-properties using setvaropts/getvaropts
VariableNamingRule: 'modify'
Location Properties:
DataLines: [2 Inf]
VariableNamesLine: 1
RowNamesColumn: 0
VariableUnitsLine: 0
VariableDescriptionsLine: 0
To display a preview of the table, use preview
检查变量 TaxiIn 和 TaxiOut 的 Type 属性。
getvaropts(opts,{'TaxiIn','TaxiOut'})
ans =
1x2 TextVariableImportOptions array with properties:
Name
Type
FillValue
TreatAsMissing
QuoteRule
Prefixes
Suffixes
EmptyFieldRule
WhitespaceRule
将变量 TaxiIn 和 TaxiOut 的类型更改为 double。
opts = setvartype(opts,{'TaxiIn','TaxiOut'},'double');
指定要导入和检查的变量的子集。
opts.SelectedVariableNames = {'TaxiIn','TaxiOut'};
使用 readtable 函数以及选项对象导入选定的变量。显示表的摘要。
T = readtable('airlinesmall.csv',opts);
summary(T)
Variables:
TaxiIn: 123523x1 double
Values:
Min 0
Median 5
Max 1451
NumMissing 37383
TaxiOut: 123523x1 double
Values:
Min 0
Median 13
Max 755
NumMissing 37364
检测并使用针对电子表格文件的导入选项
检测针对电子表格文件的导入选项,指定要导入的变量,然后读取数据。根据文件创建导入选项对象。
opts = detectImportOptions('patients.xls')
opts =
SpreadsheetImportOptions with properties:
Sheet Properties:
Sheet: ''
Replacement Properties:
MissingRule: 'fill'
ImportErrorRule: 'fill'
Variable Import Properties: Set types by name using setvartype
VariableNames: {'LastName', 'Gender', 'Age' ... and 7 more}
VariableTypes: {'char', 'char', 'double' ... and 7 more}
SelectedVariableNames: {'LastName', 'Gender', 'Age' ... and 7 more}
VariableOptions: Show all 10 VariableOptions
Access VariableOptions sub-properties using setvaropts/getvaropts
VariableNamingRule: 'modify'
Range Properties:
DataRange: 'A2' (Start Cell)
VariableNamesRange: 'A1'
RowNamesRange: ''
VariableUnitsRange: ''
VariableDescriptionsRange: ''
To display a preview of the table, use preview
修改选项对象以指定要导入的变量。
opts.SelectedVariableNames = {'Systolic','Diastolic'};
使用 readtable 以及选项对象导入指定的变量。
T = readtable('patients.xls',opts);
summary(T)
Variables:
Systolic: 100x1 double
Values:
Min 109
Median 122
Max 138
Diastolic: 100x1 double
Values:
Min 68
Median 81.5
Max 99
读取包含任意变量名称的表格数据
可以读取表格数据,同时保留包含任何字符的变量名称,包括空格和非 ASCII 字符。首先,创建一个具有任意变量名称的表,并将该表写入文本文件。然后,读回表格数据,同时保留原始变量名称。创建包含任意变量名称的表,并将表格数据写入文件 'sampletable.txt'。
LastName = {'Sanchez';'Johnson';'Li';'Diaz';'Brown'};
Age = [38;43;38;40;49];
Smoker = logical([1;0;1;0;1]);
varNames = {'Last Name','Age','Smoker (1 or 0)'};
T = table(LastName,Age,Smoker,'VariableNames',varNames)
T=5×3 table
Last Name Age Smoker (1 or 0)
___________ ___ _______________
{'Sanchez'} 38 true
{'Johnson'} 43 false
{'Li' } 38 true
{'Diaz' } 40 false
{'Brown' } 49 true
writetable(T,'sampletable.txt')
使用 readtable 读回表格数据。默认情况下,MATLAB® 将任何包含空格和非 ASCII 字符的变量名称转换为有效的 MATLAB® 标识符。例如,MATLAB® 将变量名称 'Last Name' 转换为 'LastName',将 'Smoker (1 or 0)' 转换为 'Smoker_1or0_'。要在保留变量名称的同时读取表格数据,请将 'VariableNamingRule' 参数设置为 preserve。
T_preserve = readtable('sampletable.txt',"VariableNamingRule","preserve")
T_preserve=5×3 table
Last Name Age Smoker (1 or 0)
___________ ___ _______________
{'Sanchez'} 38 1
{'Johnson'} 43 0
{'Li' } 38 1
{'Diaz' } 40 0
{'Brown' } 49 1
从文件中读取十六进制和二进制数字
可以从文件中读取十六进制和二进制数字,并将它们作为数值变量存储在表中。readtable 函数会自动读取分别包含 0x 和 0b 前缀的十六进制和二进制数字。数值使用整数数据类型存储。也可以使用导入选项来读取不带前缀的这些数字。
在文本编辑器中预览 hexAndBinary.txt 文件。它的一些列包含带前缀的十六进制和二进制数字,还有一列包含不带前缀的这些数字。
使用 readtable 读取文件。该函数检测具有 0x 和 0b 前缀的数字,并将它们作为整数存储。第三列没有前缀,因此其值被视为文本。
T = readtable('hexAndBinary.txt')
T=3×4 table
Var1 Var2 Var3 Var4
_____ ____ ________ ___________
255 255 {'C7F9'} {'Device1'}
256 4 {'05BF'} {'Device2'}
43981 129 {'F00F'} {'Device3'}
readtable 函数将数值存储在不同整数类(uint16 和 uint8)中,因为 T.Var1 的值需要 8 位以上的存储空间。
class(T.Var1)
ans =
'uint16'
//
class(T.Var2)
ans =
'uint8'
要指定用于存储从十六进制和二进制数字导入的数值的数据类型,请使用 'HexType' 和 'BinaryType' 名称-值对组参数。将值存储为有符号 32 位整数。
T = readtable('hexAndBinary.txt','HexType','int32','BinaryType','int32');
class(T.Var1)
ans =
'int32'
//
class(T.Var2)
ans =
'int32'
可以使用导入选项来检测不带前缀的十六进制和二进制数字,并为它们指定存储。为 hexAndBinary.txt 创建一个导入选项对象。
opts = detectImportOptions('hexAndBinary.txt')
opts =
DelimitedTextImportOptions with properties:
Format Properties:
Delimiter: {','}
Whitespace: '\b\t '
LineEnding: {'\n' '\r' '\r\n'}
CommentStyle: {}
ConsecutiveDelimitersRule: 'split'
LeadingDelimitersRule: 'keep'
TrailingDelimitersRule: 'ignore'
EmptyLineRule: 'skip'
Encoding: 'UTF-8'
Replacement Properties:
MissingRule: 'fill'
ImportErrorRule: 'fill'
ExtraColumnsRule: 'addvars'
Variable Import Properties: Set types by name using setvartype
VariableNames: {'Var1', 'Var2', 'Var3' ... and 1 more}
VariableTypes: {'auto', 'auto', 'char' ... and 1 more}
SelectedVariableNames: {'Var1', 'Var2', 'Var3' ... and 1 more}
VariableOptions: Show all 4 VariableOptions
Access VariableOptions sub-properties using setvaropts/getvaropts
VariableNamingRule: 'modify'
Location Properties:
DataLines: [1 Inf]
VariableNamesLine: 0
RowNamesColumn: 0
VariableUnitsLine: 0
VariableDescriptionsLine: 0
To display a preview of the table, use preview
要指定第三列应作为十六进制值导入,即使缺少前缀也要导入,请使用 setvaropts 函数来修改表中第三个变量的变量类型。将变量类型设置为 int32。
opts = setvaropts(opts,3,'NumberSystem','hex','Type','int32')
opts =
DelimitedTextImportOptions with properties:
Format Properties:
Delimiter: {','}
Whitespace: '\b\t '
LineEnding: {'\n' '\r' '\r\n'}
CommentStyle: {}
ConsecutiveDelimitersRule: 'split'
LeadingDelimitersRule: 'keep'
TrailingDelimitersRule: 'ignore'
EmptyLineRule: 'skip'
Encoding: 'UTF-8'
Replacement Properties:
MissingRule: 'fill'
ImportErrorRule: 'fill'
ExtraColumnsRule: 'addvars'
Variable Import Properties: Set types by name using setvartype
VariableNames: {'Var1', 'Var2', 'Var3' ... and 1 more}
VariableTypes: {'auto', 'auto', 'int32' ... and 1 more}
SelectedVariableNames: {'Var1', 'Var2', 'Var3' ... and 1 more}
VariableOptions: Show all 4 VariableOptions
Access VariableOptions sub-properties using setvaropts/getvaropts
VariableNamingRule: 'modify'
Location Properties:
DataLines: [1 Inf]
VariableNamesLine: 0
RowNamesColumn: 0
VariableUnitsLine: 0
VariableDescriptionsLine: 0
To display a preview of the table, use preview
读取文件并将第三列作为数值(而不是文本)导入。
T = readtable('hexAndBinary.txt',opts)
T=3×4 table
Var1 Var2 Var3 Var4
_____ ____ _____ ___________
255 255 51193 {'Device1'}
256 4 1471 {'Device2'}
43981 129 61455 {'Device3'}