How to deal with files in which rows have different numbers of columns
Show older comments
Hello everyone
I'm trying to deal with the loading and manipulation of a file (with a different extension than .txt and .data), which has the following type of structure:
#unit cell size
500 500 26.408
#unit cell vectors
1 0 0
0 1 0
0 0 1
#Atoms
46212 2
0 0 0 0 0 0 0
...
46211 0.996549 0.997788 0.75 1 0 0
808700 tensorial
0 0 1 0 0 0 1.13755e-22 0 0 0 1.13755e-22 0 0 0 1.13755e-22
...
808699 46138 46141 0 0 0 -3.83401e-23 0 1.17279e-23 -0 -3.83401e-23 1.1713e-30 -1.17279e-23 -1.1713e-30 -3.83401e-23
where the ellipsis indicates that there are as many lines as integers exist between the number in the first column preceding the ellipsis and the number in the first column just after the ellipsis. As it can be seen, between the rows "46212 2" and "808700 tensorial" all rows have seven columns, while from row "808700 tensorial" to the end of the file all rows have fifteen columns. As a note of possible interest, the first column of the line "46212 2" indicates that there will be 46212 rows with seven columns, while the first column of the line "808700 tensorial" indicates that there will be 808700 rows with fifteen columns.
My goal would be to be able to create two different variables in my MatLab-based working environment, the first containing the 46212 rows of seven columns that exist between the rows "46212 2" and "808700 tensor", and the second containing the 808700 rows of fifteen columnas that exist between the row "808700 tensor" and the end of the file. How could this be done?
I would also be very interested in knowing if it is possible for Matlab itself to detect the number of rows with seven and fifteen columns, respectively, in such a way that I can use this method for files of the same type that do not necessarily have 46212 rows of seven columns and 808700 rows of fifteen columns, as in this case.
Accepted Answer
More Answers (2)
Walter Roberson
on 8 Dec 2023
I would suggest using textscan with appropriate format for what you are expecting to read, and using explicit repeat counts. Something along the lines of
atomsinfocell = textscan(fid, AtomsFmt, Num_Atoms);
possibly with the CollectOutput option turned on.
Categories
Find more on Cell Arrays 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!