Reading data with specific format

2 views (last 30 days)
I have a text file something similar to below.
Time
10
Atoms
100
1 2 .1 .3 .4
2 1 .4 .6 .7
3 1 .5 .6 .8
Time
20
Atoms
100
1 2 .5 .6 .4
2 1 .4 .6 .9
3 1 .5 .6 .4
Time
30
Atoms
100
1 2 .5 .6 .4
2 1 .4 .7 .9
3 1 .7 .6 .1
Time
............
............
The text file is repeated for many times. Now I want to extract the data which is in the format of '%f%f%f%f%f'. i.e I need to generate an matrix as below.
[1 2 .1 .3 .4
2 1 .4 .6 .7
3 1 .5 .6 .8
1 2 .5 .6 .4
2 1 .4 .6 .9
3 1 .5 .6 .4
1 2 .5 .6 .4
2 1 .4 .7 .9
3 1 .7 .6 .1
............
...........]
How to do that without using loop?
Thanks

Accepted Answer

Star Strider
Star Strider on 24 Nov 2016
It’s not possible to do it without a loop. The reason is that you have to do something similar to:
fidi = fopen( ... ,'rt');
k1 = 1;
while ~feof(fidi)
D{k1} = textscan(fidi, '%f%f%f%f', 'HeaderLines',4, 'CollectOutput',true);
fseek(fidi, 0, 0)
k1 = k1 + 1;
end
fclose(fidi)
The code will stop when it hits a text line, then with the fseek call it will advance to the next line, skip it and the next 3 header lines, then continue through until it encounters a valid ‘end-of-file’ indicator, then stop. If there is no valid ‘end-of-file’ indicator, this becomes an infinite loop, so be mindful of that possibility.
NOTE This is UNTESTED CODE. It should work with appropriate modifications. You may need to add additional name-value pair arguments to the textscan call to make it work with your file.

More Answers (0)

Categories

Find more on Data Import and Export in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!