How to pick numbers in text file in matrix format

1 次查看(过去 30 天)
Hello,
From past few days I was trying to convert the attached text file to matrix. The text file includes characters and numbers, but I only want the numbers to be picked from the text file. For example, the text file reads:
No.1 >
17.698 0.000 0.000 0.000 0.000 17.698 0.000 0.000 0.000 17.698
0.000 0.000 17.698 0.000 0.000 0.000 0.000 0.000 0.000 0.000
29.209
No.2 >
0.000 0.000 8.754 0.000 17.509 0.000 8.754 0.000 0.000 8.754
0.000 0.000 8.754 0.000 0.000 0.000 0.000 0.000 0.000 0.000
47.473
No.3 >
0.000 0.000 6.720 0.000 6.720 0.000 6.720 6.720 6.720 0.000
0.000 0.000 6.720 0.000 0.000 0.000 0.000 0.000 0.000 0.000
59.679
What is need is the matrix having 3 rows and 21 columns:
17.698 0.000 0.000 0.000 0.000 17.698 0.000 0.000 0.000 17.698 0.000 0.000 17.698 0.000 0.000 0.000 0.000 0.000 0.000 0.000 29.209
0.000 0.000 8.754 0.000 17.509 0.000 8.754 0.000 0.000 8.754 0.000 0.000 8.754 0.000 0.000 0.000 0.000 0.000 0.000 0.000 47.473
0.000 0.000 6.720 0.000 6.720 0.000 6.720 6.720 6.720 0.000 0.000 0.000 6.720 0.000 0.000 0.000 0.000 0.000 0.000 0.000 59.679

采纳的回答

Stephen23
Stephen23 2019-2-24
编辑:Stephen23 2019-2-24
Simple and efficient:
opt = {'HeaderLines',1, 'CollectOutput',true, 'EndOfLine','>', 'WhiteSpace',' \n\r\t'};
fmt = [repmat('%f',1,21),'%*s'];
[fid,msg] = fopen('sample.txt','rt');
assert(fid>=3,msg)
C = textscan(fid,fmt,opt{:});
fclose(fid);
Giving:
>> C{1}
ans =
Columns 1 through 7
17.6980 0 0 0 0 17.6980 0
0 0 8.7540 0 17.5090 0 8.7540
0 0 6.7200 0 6.7200 0 6.7200
Columns 8 through 14
0 0 17.6980 0 0 17.6980 0
0 0 8.7540 0 0 8.7540 0
6.7200 6.7200 0 0 0 6.7200 0
Columns 15 through 21
0 0 0 0 0 0 29.2090
0 0 0 0 0 0 47.4730
0 0 0 0 0 0 59.6790

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Text Data Preparation 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by