Difficulty using textscan to read a file with varying formats

1 view (last 30 days)
I am trying to read a file of the following format: (using Matlab R2011b)
0.41 8.24 3.57 -6.24 9.27
0.41 8.24 3.57 6 9.27
1000 a bunch of text 3 4 5
....
repeats
...
I want to read the first two lines that just contain numbers independently of the last.
I tried:
filedata = textscan(str, '%5.2f%5.2f%5.2f%5.2f%5.2f','CollectOutput',1);
But that also starts scanning the third line so that:
filedata{1}
ans =
410.0000e-003 8.2400e+000 3.5700e+000 -6.2400e+000 9.2700e+000
410.0000e-003 8.2400e+000 3.5700e+000 6.0000e+000 9.2700e+000
1.0000e+003 NaN NaN NaN NaN
I'd like to get text scan to just read only the first format with just numbers and stop. Then I would procede on to the second format with a different text scan.
Any suggestions on how to do this?
I know that if that last line started with a text character it would work, I've tested this. But that's not how the file is formated. Also, the number of lines in each section will actually vary.
It seems that textscan delineates blocks of data for 'CollectOutput' based on that first character somehow but I can't find any documentation on the particulars of that other than this tip in the help file for textscan:
When textscan reads a specified file or string, it attempts to match the data to the format string. If textscan fails to convert a data field, it stops reading and returns all fields read before the failure.

Accepted Answer

Walter Roberson
Walter Roberson on 12 Jun 2012
NumLines = 2;
filedata = textscan(str, '%5.2f%5.2f%5.2f%5.2f%5.2f', NumLines, 'CollectOutput',1);

More Answers (0)

Categories

Find more on Text Data Preparation in Help Center and File Exchange

Tags

Products

Community Treasure Hunt

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

Start Hunting!