MATLAB Answers

Problem using textscan multiple times for one file

조회 수: 2(최근 30일)
jeon
jeon 2021년 8월 11일
댓글: Walter Roberson 2021년 8월 11일
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);

답변(1개)

Stephen
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