在 Matlab 上读取逗号分隔的文本文件

Reading Text file comma seperated on Matlab

我正在尝试读取如下所示的逗号分隔文本文件:

2017-10-24,01:17:38,2017-10-24,02:17:38,+1.76,L,Meters
2017-10-24,02:57:31,2017-10-24,03:57:31,+1.92,H,Meters
2017-10-24,05:53:35,2017-10-24,06:53:35,+1.00,L,Meters
2017-10-24,10:45:01,2017-10-24,11:45:01,+2.06,H,Meters
2017-10-24,13:27:16,2017-10-24,14:27:16,+1.78,L,Meters
2017-10-24,15:07:16,2017-10-24,16:07:16,+1.92,H,Meters
2017-10-24,18:12:08,2017-10-24,19:12:08,+0.98,L,Meters

到目前为止我的代码是:

LT_data = fopen('D:\Beach Erosion and Recovery\Bournemouth\Bournemouth Tidal Data\tidal_data_jtide.txt');% text file containing predicted low tide times

LT_celldata = textscan(LT_data,'%D %D %D %D %d ','delimiter',',')'

一切正常。需要编辑格式规范。

file = 'D:\Beach Erosion and Recovery\Bournemouth\Bournemouth Tidal Data\tidal_data_jtide.txt'
fileID = fopen(file);
LT_celldata = textscan(fileID,'%D%D%D%D%d%[^\n\r]','delimiter',',')

对于混合数据类型,我建议 readtable。这会将您的数据直接读入 table 对象,而无需指定格式规范或使用 fopen

t = readtable( 'myFile.txt', 'ReadVariableNames', false, 'Delimiter', ',' );

然后你就可以轻松操作数据了

% Variable names in the table
t.Properties.VariableNames = {'Date1', 'Time1', 'Date2', 'Time2', 'Value', 'Dim', 'Units'};

% Create full datetime object columns from the date and time columns
t.DateTime1 = datetime( strcat(t.Date1,t.Time1), 'InputFormat', 'yyyy-MM-ddHH:mm:ss' );

如果你知道格式,你可以在readtable中指定'format' 属性,它会在读取时转换数据。