extracting matrices of numbers from a text file (txt) also containing words
1 回表示 (過去 30 日間)
古いコメントを表示
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.
2 件のコメント
Chuguang Pan
2024 年 3 月 20 日
編集済み: Chuguang Pan
2024 年 3 月 20 日
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")
採用された回答
dpb
2024 年 3 月 20 日
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 件のコメント
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Data Import and Export についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!