- 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.
Problem using textscan multiple times for one file
4 次查看(过去 30 天)
显示 更早的评论
Hello.
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);
fclose(fileID);
0 个评论
回答(1 个)
Stephen23
2021-8-11
编辑:Stephen23
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:
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Climate Science and Analysis 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!