NEED TO READ A FILE AND STORE VALUES
Show older comments
Good morning,
I'm having trouble reading a .txt file in matlab. The file contains different data with different formats delimited from headerlines.
The file structure is as follows:
Field Time R1:X R1:Y R1:Z R2:X R2:Y R2:Z R3:X R3:Y R3:Z
1 0.0000 196.1938 98.836 986.1718 194.511 94.529488 962.833557 235.324265 89.228859 961.438660
...
Sample # Fx Fy Fz Mx My Mz Fx Fy Fz Mx My Mz EMG 1 EMG 2 EMG 3 EMG 4 EMG 5 EMG 6 EMG 7 EMG 8 BASA BASB
1 6.901305 17.359007 -439.079376 41616.441406 -5983.515625 602.935791 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 -0.044708 -0.041351 -0.043640 -0.044708 -0.045319 -0.044250 -0.042877 -0.042725 -0.004272 4.121094
.....
Force Plate 1 Force Plate 2
Sample # COP:X COP:Y COP:Z Ref:X Ref:Y Ref:Z Force:X Force:Y Force:Z Moment:X Moment:Y Moment:Z
1 244.158 161.003 0.000 231.769 254.000 0.000 -6.901 17.359 439.079 -40833.019 -5439.495 -612.130
......
I need to read all the data from the first header line and skip them until the second header line. Then i need to read all the data from the second header line and store the column BASA in an array. Then all the data from the third header line and store the columns COP:X, COP:Y and COP:Z in 3 different arrays.
Thanks in advance for the help.
Accepted Answer
More Answers (1)
Walter Roberson
on 1 Feb 2022
1 vote
The easiest way is probably to use fileread() to read the entire file as a character vector. Then use string operations or regexp() to locate the headers, and split the single character vector at that point, into separate character vectors that each include the headers and all associated data. Then you can use textscan() to parse each of the character vectors, using appropriate format information and number of headers.
Instead of using fileread(), your style might prefer readlines() which reads the file and breaks it up into a cell array of character vectors. You can then scan through the character vectors looking for the boundaries, and use indexing to extract subsections. You would not have to use 'headerlines', as you would could use fixed offsets into the subset cell array. However, as you would have all the data one line at a time in a cell array, it would probably not be as efficient to read the data in as it could be if you were to put the data back into a continguous block and use textscan() or sscanf()
Categories
Find more on Large Files and Big Data 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!