MATLAB Answers

Text File Read and Separate the Specific Rows

7 views (last 30 days)
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?

Accepted Answer

Walter Roberson
Walter Roberson on 13 Nov 2020
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 Comments
Walter Roberson
Walter Roberson on 14 Nov 2020
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.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!