Importing only specific data from a text file

5 次查看(过去 30 天)
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 个评论
Michael
Michael 2014-6-18
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 2014-6-18
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.

请先登录,再进行评论。

回答(0 个)

类别

Help CenterFile Exchange 中查找有关 String Parsing 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by