Importing only specific data from a text file

6 views (last 30 days)
Michael
Michael on 18 Jun 2014
Commented: dpb on 18 Jun 2014
I have a text file with data such as the following:
M13=1 M14=5000 M15=0 M16=-12.5 M17=100 etc
the problem is I only want to import some, not all of this data, and save them to an mfile.
How can I tell matlab what data to include and what to exclude?
  9 Comments
Michael
Michael on 18 Jun 2014
there is no pattern and no repeats. There's several thousand lines of variables, I only need the values of about 20 of them. Some start with P some start with M, some start with Q, etc. I'm only interested in about 20 that start with M, if that helps.
dpb
dpb on 18 Jun 2014
I'd recommend to forget about only reading the lines wanted in place of scarfing up the whole file as string array and then doing either regexp or regular string-matching to find the rows desired. Then, having that array index, delete the remaining lines and use textscan or whatever other useful i/o functions (again, perhaps including regular expressions) to convert.
For only "several thousand" unless you know the ones desired are within the first few lines it's probably just as fast to read the whole file as it is to process line-by-line.
To get the file into memory
file=textread('yourfile.dat', '%s', 'delimiter', '\n', ...
'whitespace', '');
If you were able to a priori know a range of lines within the file, you could limit the amount imported by adding 'headerlines' and a repeat count on the format to load only a given section of known size. But, that's a purely mechanical count so would have to know something about the file structure independent of content.

Sign in to comment.

Answers (0)

Community Treasure Hunt

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

Start Hunting!