sscanf to extract numbers from string
Afficher commentaires plus anciens
Hi everyone,
I have a data file like this:
1 .00 80.00 160.00 240.00 320.00 400.00 480.00 560.00 640.00 720.00
1 -250.00-250.00-250.00-255.00-255.00-260.00-265.00-270.00-265.60-260.00
1 800.00 880.00 960.001040.001120.001200.001280.001360.001440.001520.00
1 -255.00-255.00-263.30-286.70-310.60-320.00-313.90-290.00-267.80-260.00
....
The format doens't change.
I try to read each line using sscanf, but when the numbers doenst have space, I can't read them.
In otherwords, when I use:
ff = fgetl(fid)
aff = sscanf(ff,'%f')
This works fine for the first line, because the numbers has space between them.
But doens't work for the rest of lines.
I also tried the command:
ff = fgetl(fid)
aff = sscanf(ff,'%2f %7.2f%7.2f%7.2f%7.2f%7.2f%7.2f%7.2f%7.2f%7.2f%7.2f',[1 11])
But without success.
Someone can help me?
Best regards.
Réponse acceptée
Plus de réponses (1)
sscanf format is different from sprintf. In particular there's no .2 notation for %f, so your .2 is interpreted as a literal .2 and of course does not match anything.
There's no need to fgetl and then sscanf. You can read the whole file in one go with fscanf instead, so:
fid = fopen(somefile, 'rt');
assert(fid > 0, 'Failed to open file');
aff = fscanf(fid, '%2f %7f%7f%7f%7f%7f%7f%7f%7f%7f%7f', [11, Inf])'
fclose(fid);
2 commentaires
Walter Roberson
le 28 Mar 2019
This turns out to fail on the space 960.00 no-space 1040.11 pair on the third line.
Bruno Goncalves
le 28 Mar 2019
Modifié(e) : Stephen23
le 28 Mar 2019
Catégories
En savoir plus sur Spectral Estimation dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!