Clear Filters
Clear Filters

Text File Read and Separate the Specific Rows

6 views (last 30 days)
Hi, I have a text file like this and it is just part of it;
#% table: monthly mean temperture
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);
TIME_BEGIN = datacell{1}; TIME_END = datacell{2}; TEMPERATURE = datacell{3};
mask = MB == 9 | ME == 9; %or perhaps you want & instead of |
september_MMT = MMT(mask,:);
Ahmet Hakan UYANIK
Ahmet Hakan UYANIK on 14 Nov 2020
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 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!