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.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1646751/image.png)
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 Analysis 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!