从特定行读取文本文件

时间:2017-11-21 13:43:57

标签: matlab text-files

如何在matlab中读取包含以下文本的文本文件?

Port:              P988
Site:              Bournemouth
Latitude:          50.71433
Longitude:         -1.87486
Start Date:        01JUL2017-00.00.00
End Date:          31JUL2017-23.45.00
Contributor:       National Oceanography Centre, Liverpool
Datum information: The data refer to Admiralty Chart Datum (ACD)
Parameter code:    ASLVBG02 = Surface elevation (unspecified datum) of the water body by bubbler tide gauge (second sensor)
  Cycle    Date      Time    ASLVBG02   Residual  
 Number yyyy mm dd hh mi ssf         f          f 
     1) 2017/07/01 00:00:00     1.758M     0.046M 
     2) 2017/07/01 00:15:00     1.752M     0.045M 
     3) 2017/07/01 00:30:00     1.754M     0.055M 
     4) 2017/07/01 00:45:00     1.753M     0.064M 
     5) 2017/07/01 01:00:00     1.763M     0.081M 
     6) 2017/07/01 01:15:00     1.768M     0.088M 
     7) 2017/07/01 01:30:00     1.756M     0.074M 
     8) 2017/07/01 01:45:00     1.753M     0.067M 
     9) 2017/07/01 02:00:00     1.749M     0.060M 
    10) 2017/07/01 02:15:00     1.737M     0.051M 

我正在寻找行

1) 2017/07/01 00:00:00     1.758M     0.046M

起。有可能每天为ASLVBG02绘制时间。每天由96行组成。

2 个答案:

答案 0 :(得分:0)

fid = fopen('myfile.txt','r');

% Tweak and parametrize it as necessary, since data types and delimiters are not 100% clear in the data excerpt you provided...
tab = textscan(fid,your_format_spec,'Headerlines',11);

fclose(fid);

有关textscan功能的更多信息:https://mathworks.com/help/matlab/ref/textscan.html

为了处理文件开头的不必要的行,您所要做的就是指定一个正确的Headerlines参数。

答案 1 :(得分:0)

如上所述,请使用textscan。根据您的样本日期,以下似乎在Octave中运行良好:

% Open the file (replace by actual file name)
fid = fopen('test_file.txt');

% Read data with following format
% 1) 2017/07/01 00:00:00     1.758M     0.046M 
data = textscan(fid,'%d %c %f %c %f %c %f %f %c %f %c %f %f %c %f %c','HeaderLines',11);

% Close the file
fclose(fid);

% Re-arrange time data
yyyy = data{1,3};
MM = data{1,5};
dd = data{1,7};
hh = data{1,8};
mm = data{1,10};
ss = data{1,12};
date_time = datenum(yyyy,MM,dd,hh,mm,ss);

% Get ASLVBG02 data
ASLVBG02 = data{1,13};

% Plot the data
plot(date_time,ASLVBG02)
grid on
datetick('HH:MM:SS')
ylabel('ASLVBG02')

它产生以下图:

enter image description here