extracting matrices of numbers from a text file (txt) also containing words
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
I have a txt file consisting of numbers and words as you can see in the attachment.
I have to create two matrices M1 and M2 with only the numbers (see figure). How can they be generated?
note: I have several such files. The columns of the two matrices are always the same (6 columns for M1 and 15 columns for M2); the rows are variable.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1646751/image.png)
2 Commenti
Chuguang Pan
il 20 Mar 2024
Modificato: Chuguang Pan
il 20 Mar 2024
The readmatrix function can read the numbers. But it returns a big matrix, which contain both M1 and M2 as submatrix.
A=readmatrix("test.txt")
Risposta accettata
dpb
il 20 Mar 2024
f='https://www.mathworks.com/matlabcentral/answers/uploaded_files/1646741/test.txt';
m=readmatrix(f);
whos m
[m(1:5,:);m(end-5:end,:)]
shows that readmatrix can find numeric data but as the other poster notes, isn't all that clean as towards your needed/intended result.
m=m(~all(m,2),:); % remove rows that aren't all NaN and then see what have left
whos m
[m(end-9:end,:)]
ix2=all(isfinite(m),2);
m2=m(ix2,:)
m1=m(~ix2,:); m1=m1(:,all(isfinite(m1)))
Alternatively, you could parse the file as text looking for the FORTRAN format string just ahead of each array and the -1 in the record past each array and then read/convert those sections directly.
Depending upon how large real files might be, would be interesting to see the performance difference between the explicit conversion and then the builtin parsing inside the readmatrix routine.
0 Commenti
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Data Import and Export in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!