Read a complex text file and then rearrange it
Mostra commenti meno recenti
Hello people!
I have a .txt file I need to import in MATLAB, read and then rearrange. But let's stick to the reading part for now. The text file may be found here:
As you may notice the file structure is several lines of header, a four column matrix, some lines of header again and then a five column matrix until the end of the file.
What do I need to keep: 1. some numbers from both header groups 2. 2 first columns from the first matrix 3. all columns from the last matrix
My inquiry is: 1. How can I read the first four headers and store them (numbers as numbers and text as text)? 2. How can I read the first two columns of the first matrix and ignore the others. Note that 48 is the length of number of rows of the first matrix. Is it possible to keep the first two columns in two separate single column matrices A(n,1)? 3. Read the next set of three headers like in point 1 4. How can I real all the columns of the last matrix and store the data in five single column matrices? Note that 680 is the number of rows of the last matrix.
I have some knowledge of FORTRAN but it's been too long since I used it, plus I don't own a FORTRAN license anymore. MATLAB is my only option. So I would appreciate it if a brief desription followed each code line.
Thank you in advance!
Giorgos
Risposta accettata
Più risposte (1)
Giorgos Tassis
il 16 Gen 2013
0 voti
1 Commento
Thorsten
il 16 Gen 2013
One nice think about Matlab is that many functions are vectorized so you wouldn't need for loop as often as in other languages.
Your example works if every line contains a single whole number (%d). If there are more numbers sscanf will return all numbers, and you have to assign them to num(i, :), i.e, the i'th row in matrix num:
for i = 1:4
s(i) = fgets(fid);
num(i, :) = sscanf(s(i), '%d');
end
And you can even write it more concise
for i = 1:4
num(i, :) = sscanf(fgets(fid), '%d');
end
Categorie
Scopri di più su Programming in Centro assistenza e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!