Text File Read and Separate the Specific Rows
조회 수: 3 (최근 30일)
이전 댓글 표시
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?
댓글 수: 0
채택된 답변
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
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 Center 및 File Exchange에서 Data Import and Export에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!