proper way of reading data from text file
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
The attached file is example data file. I need to store each element of line 2-3, 5-6, 8-9. The original file is bigger than this example. How can I store these numeric values of the related lines?
0 commentaires
Réponse acceptée
Stephen23
le 31 Déc 2016
Modifié(e) : Stephen23
le 31 Déc 2016
Here is one easy way to get all of that data into one matrix, using fileread and sscanf:
>> str = fileread('data.txt');
>> vec = sscanf(str,'%f');
>> mat = reshape(vec,[],3)'
mat =
Columns 1 through 7
4 1 2016 3570 1 1 1
4 1 2016 3600 2 -4 1
4 1 2016 3600 3 5 1
Columns 8 through 14
4 1 2016 1519.3 0 0 0.00014496
4 1 2016 6786.1 0 0 -0.00016785
4 1 2016 11876 0 0 -5.722e-005
Columns 15 through 20
0.76367 0.0064783 0.14664 0.0004673 -2656.4 0.00073242
0.64332 0.0091085 -0.69379 0.0012169 -2656.1 0.00067139
0.52564 0.0081682 -0.65228 0.001173 -2656.2 0.00073242
To automatically detect how many groups there are you could do something like this:
>> grp = numel(regexp(str,'^\d\d\s+\d\d\s+\d{4}\s+\d{4}\s*$','lineanchors'))
grp =
3
>> mat = reshape(vec,[],grp)'
Note that this method assumes that your data is all numeric, and that every group contains exactly the same number of values.
0 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Text Files dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!