Text File Read and Separate the Specific Rows

조회 수: 5 (최근 30일)
Ahmet Hakan UYANIK
Ahmet Hakan UYANIK 2020년 11월 13일
댓글: Walter Roberson 2020년 11월 14일
Hi, I have a text file like this and it is just part of it;
#% table: monthly mean temperture
#% TIME_BEGIN TIME_END TEMPERATURE
19570901 19570930 13.2
19571001 19571031 10.4
19571101 19571130 6.2
... ... ...
this time series according to data is continues. I would like to read this file first. Then separate the rows of Septembers which is represented in the 5th and 6th numbers of the first and second columns. Which way can I use to do it?

채택된 답변

Walter Roberson
Walter Roberson 2020년 11월 13일
filename = 'YourFile.txt';
fid = fopen(filename, 'rt');
datacell = textscan(fid, '%{yyyyMMdd}D %{yyyyMMdd}D %f', 'headerlines', 2);
fclose(fid);
TIME_BEGIN = datacell{1}; TIME_END = datacell{2}; TEMPERATURE = datacell{3};
MMT = table(TIME_BEGIN, TIME_END, TEMPERATURE);
[YB,MB,DB] = ymd(MMT.TIME_BEGIN);
[YE,ME,DE] = ymd(MMT.TIME_END);
mask = MB == 9 | ME == 9; %or perhaps you want & instead of |
september_MMT = MMT(mask,:);
  댓글 수: 2
Ahmet Hakan UYANIK
Ahmet Hakan UYANIK 2020년 11월 14일
Thank you very much. I understand every step that you did in the code and reshaped it according to my code. However only thing that I didn't get is 'rt' in fid = fopen(filename, 'rt');
Why did you write 'rt'? What was its purpose? because I used fopen without 'rt' and it works well.
Walter Roberson
Walter Roberson 2020년 11월 14일
The default for fopen() is 'r' which asks for read mode. 'rt' asks for read mode and specifies that carriage-return + linefeed pairs are to be treated as line terminators. If you are running on Windows and your file just happens to use the old style CR+LF between lines instead of the newer style LF only, then the default would not strip out the CR, and that can interfere with some ways of processing files.
It happens that when you use textscan() that by default CR is treated as whitespace that would be ignored in nearly all cases, so even if you did have CR+LF you would be okay, but I tend to put in the 'rt' automatically if I suspect the user might be using Windows, so that I do not need to think any further about whether I need to handle stray CR specially.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Text Files에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by