我想导入一个txt文件,该文件具有HH:MM:SS
格式的时间戳列。我试过一些不同的东西,但都不走运。希望有人能帮助,我已经附上了我试图导入的表和我尝试使用的matlab代码。
% Import the data from the text file
data = readtable('data.txt');
% Converting the time values to datetime format
time_values = datetime(data(:, 1), 'InputFormat', 'HH:mm:ss');
% Separating the remaining values into a separate variable or column
other_values = data(:, 2:end);
A列 | B列 | 00.00.01 | 13日05254116 |
---|---|
00.00.02 | 13日05254116 |
00.00.03 | 13日05254116 |
00.00.04 | 12日8976404 |
00.00.05 | 12日8976404 |
00.00.06 | 12日74349886 |
00.00.07 | 12日74349886 |
00.00.08 | 12日59011097 |
00.00.09 | 12日43747122 |
如果您不指定导入选项,readtable()
将扫描文件并尝试自行解决许多问题。有时它会出错,除非你明确地解释如何解读文本。如果您尝试直接导入文件,您将得到如下内容:
>> filename = 'timetableexample.txt' ;
data = readtable(filename)
data =
9×2 table
Var1 Var2
_______________ ________
{'00.00.01 13'} 5254116
{'00.00.02 13'} 5254116
...
这显然是错误的。有几个问题在你的文本文件的格式,这是防止readtable
做这样一个文本文件的顺利导入:
文件的第一个问题是,逗号,
将在每行上被检测到,readtable
将将其解释为delimiter
列。这就是为什么当您尝试直接导入时,最终会在错误的位置分割表。
为了缓解这个问题,我们可以手动指定分隔符。我假设在您的文件中,分隔符是space
字符。如果真正的分隔符是制表符,请相应地调整代码(使用't'
而不是' '
)。
首先,我们通过运行以下命令获得一个delimitedTextImportOptions
对象:
opts = detectImportOptions(filename) ;
您可以验证自动检测分隔符确实是错误的:
>> opts.Delimiter
ans =
1×1 cell array
{','}
用右分隔符
代替opts.Delimiter = {' '} ;
现在,如果您尝试使用这个新选项读取文件,列分隔是正确的,但导入仍然有问题:
>> data = readtable(filename,opts)
data =
9×2 table
Var1 Var2
____________ ____
{'00.00.01'} NaN
{'00.00.02'} NaN
这是因为Matlab的默认十进制分隔符是点.
,而不是许多欧洲国家使用的逗号,
。为了纠正这一点,我们将告诉Matlab首先将该列作为文本导入(然后我们将修改文本,以便Matlab可以将其转换为数字)。
VariableTypes
:
>> opts.VariableTypes
ans =
1×2 cell array
{'char'} {'double'}
我们将替换为:
opts.VariableTypes = {'char','char'} ;
最后:
data = readtable(filename,opts)
data =
9×2 table
Var1 Var2
____________ _______________
{'00.00.01'} {'13,05254116'}
{'00.00.02'} {'13,05254116'}
我们的列都被正确导入了,但到目前为止只是作为文本导入的。接下来,我们将替换每列中的非常规字符,并将它们替换为Matlab对当前类型(datetime
和double
)的期望。我们将使用strrep()
函数。然后将此文本转换为适当的时间/值就变得很简单了。
我认为困扰您的是自动导入选项和您的特定文件格式之间的不匹配。现在解释一下,我不会逐行详细说明代码,只给您完整的代码来导入这样的文件:
filename = 'timetableexample.txt' ;
opts = detectImportOptions(filename);
% modify the import options we need
opts.Delimiter = {' '} ;
opts.VariableTypes = {'char','char'} ;
data = readtable(filename,opts) ; % read the table
strTime = table2cell(data(:,1)) ; % extract column 1 in a cell array
strTime = strrep(strTime,'.',':') ; % replace '.' with ':'
% Now you can convert to datetime object
time_values = datetime(strTime, 'InputFormat', 'HH:mm:ss') ;
strData = table2cell(data(:,2)) ; % extract column 2 in a cell array
strData = strrep(strData,',','.') ; % replace ',' with '.'
% Convert cell array of char into a double array
other_values = str2double(strData) ;