MATLAB: Sscanf to extract numbers from string

read datasscanf

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.

Best Answer

textscan() and fscanf() and sscanf() all have the same problem: Their counts for formats such as %7f start only after leading space has been skipped. You can see this in particular in the space 960.00 no-space 1040.11 entries on the third line: the count starts after the space, so the 960.001 is what gets parsed.
To handle fixed-width inputs, you have a small number of choices:
  1. There is a File Exchange contribution to handle fixed-width input
  2. if you bash your head against the problem for long enough you can convince textscan() to work fixed width; this is not easy
  3. you can use array indexing to break the text into fields that you convert to numeric such as with str2double
  4. you can use regexp to break the text into fields that you convert to numeric such as with str2double
  5. with R2017a or later, you can use readtable() in a fixed-width mode. See https://www.mathworks.com/help/matlab/ref/matlab.io.text.fixedwidthimportoptions.html
regexp() can be pretty useful for a purpose such as this.
Related Question