Reading a text file: Skip lines in the middle of data
9 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Ben Morrow
am 24 Mai 2018
Beantwortet: Ben Morrow
am 24 Mai 2018
Hello,
I am trying to import data into an array from a text file that looks something like this:
Header lines
Header lines
Header lines
Var1 Var2 Var3 Var4
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4
mid data header lines
mid data header lines
Var1 Var2 Var3 Var4
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4
mid data header lines
mid data header lines
Var1 Var2 Var3 Var4
1 2 3 4
1 2 3 4
... etc until nData
I want to grab all of Var2 into one 1xndata array. The mid data header lines occurs every 5 lines (the real file is every 50 lines, I wanted to spare you). The header is no problem I can skip it and read Var2 up to the first mid data header. I cant figure out how to skip the mid data to continue the fscanf.
3 Kommentare
Guillaume
am 24 Mai 2018
it might be important to note I am using MATLAB 2009
That's unfortunate. In R2018a, you only need three lines of code to read the whole file, using the DataLine property of the readtable options.
As suggested by Rik, I would simply read the whole file in one go (with fileread), split it into lines (IIRC, strsplit didn't exist in R2009, so use regexp) then get rid of the offending lines and convert the rest.
Akzeptierte Antwort
Weitere Antworten (1)
Ameer Hamza
am 24 Mai 2018
Try fgetl(). Read each line one by one and then decide which line to process or ignore. Also after reading the line, use textscan() to extract numeric values. For example, if you detect a line is valid for processing i.e. contains number then you can use
numbers = textscan(line, '%f') % line is char array
numberToKeep = numbers(2) % you only need second number.
0 Kommentare
Siehe auch
Kategorien
Mehr zu Data Import and Export finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!