How to pick numbers in text file in matrix format

1 visualizzazione (ultimi 30 giorni)
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

Risposta accettata

Stephen23
Stephen23 il 24 Feb 2019
Modificato: Stephen23 il 24 Feb 2019
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

Più risposte (0)

Categorie

Scopri di più su Text Data Preparation 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!

Translated by