How to pick numbers in text file in matrix format

1 vue (au cours des 30 derniers jours)
Learner
Learner le 23 Fév 2019
Commenté : Learner le 24 Fév 2019
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

Réponse acceptée

Stephen23
Stephen23 le 24 Fév 2019
Modifié(e) : Stephen23 le 24 Fév 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
  1 commentaire
Learner
Learner le 24 Fév 2019
It is working very well. Thanks.

Connectez-vous pour commenter.

Plus de réponses (0)

Community Treasure Hunt

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

Start Hunting!

Translated by