MATLAB Answers

Problem using textscan multiple times for one file

2 ビュー (過去 30 日間)
jeon 2021 年 8 月 11 日
コメント済み: Walter Roberson 2021 年 8 月 11 日
I'm going to read yyy-MM-dd HH:mm:ss from this text file,
put it in ‘ymdt6’, read the two-digit numerical data in the next columns, and put it in ‘tide6’. There was no problem when 'ymdt6' and 'tide6' were done in individual files(YMDT6 -> 43200x1 datetime TIDE6 -> 43200x1 double).But when I did it in one file like below, ‘tide6’ comes out as a empty 0×1 cell array.
How can I solve this problem?
fileID = fopen('data_2013_DT_DT_5_201306_KR.txt');
ymdt6 = textscan(fileID, ...
'%19c %*[^\n]', 'HeaderLines', 4);
B = [ymdt6{:}];
C = cellstr(B);
tide6 = textscan(fileID, ...
'%*s %*s %s %*[^\n]', 'HeaderLines', 4);
D = [tide6{:}];
YMDT6 = datetime(C, 'InputFormat', 'yyyy-MM-dd HH:mm:ss');
TIDE6 = str2double(D);

回答 (1 件)

Stephen 2021 年 8 月 11 日
編集済み: Stephen 2021 年 8 月 11 日
"How can I solve this problem?"
After calling TEXTSCAN the first time the file pointer will be at (or near) the end of the file. So before the second TEXTSCAN you will need to send the file pointer back to the start of the file using FREWIND:
But your current approach is rather complex. You should simplify your code, in particular:
  • call TEXTSCAN just once (instead of twice),
  • and specify the DATETIME and numeric formats correctly, so that you import those data type without needing to fiddle around with converting text afterwards.
As an alternative you could use READTABLE, which might automagically detect those data types.
If you had uploaded a sample file I would have shown you how to write more efficient code.
  1 件のコメント
Walter Roberson
Walter Roberson 2021 年 8 月 11 日
Also I suspect you need Headerlines 5 not 4.



Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by