Search code examples
matlabtextscan

Matlab textscan with fixed width


I have to read a file like this

10001   3          5.0000      30.0         0.0000      25.6         0.0000      10.0
10002   1         25.0000                   0.0000                   4.6887      58.2
10003   5         45.0000      20.0         0.0000                  14.7608          
10004   5         65.0000                   0.0000                   8.8791          
10005   1         85.0000                   0.0000                   6.3128      00.0

where the file format like this '%5i%5i%%10.4f%8.1f%10.4f%8.1f%10.4f%8.1f'

I'm using the following code

n_xyz_filename = input('\nSelect the file. ', 's');
n_xyz_file = fopen(n_xyz_filename, 'r');
n_xyz = textscan(n_xyz_file, '%5i%5i%10.4f%8.1f%10.4f%8.1f%10.4f%8.1f');
fclose(n_xyz_file);

But I keep on getting the following error

??? Error using ==> textscan Badly formed format string.

I really can't get it!

EDIT

As the answer said, the right code is:

n_xyz_filename = input('\nSelect the file. ', 's');
n_xyz_file = fopen(n_xyz_filename, 'r');
n_xyz = textscan(n_xyz_file, '%5d%5d%10.4f%8.1f%10.4f%8.1f%10.4f%8.1f');
fclose(n_xyz_file);

with the "d" (stand for decimal) instead of "i"


Solution

  • The problem is the format specifier i, which is not recognized by textscan. In case you wanted to indicate an integer, you should've used d. The correct syntax is therefore:

    n_xyz = textscan(n_xyz_file, '%5d%5d%10.4f%8.1f%10.4f%8.1f%10.4f%8.1f');