extracting matrices of numbers from a text file (txt) also containing words
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Alberto Acri
el 20 de Mzo. de 2024
Respondida: dpb
el 20 de Mzo. de 2024
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 comentarios
Chuguang Pan
el 20 de Mzo. de 2024
Editada: Chuguang Pan
el 20 de Mzo. de 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")
Respuesta aceptada
dpb
el 20 de Mzo. de 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 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Data Import and Export en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!