Avoid typing conversion specifier for every column in large table in `textscan`

4.7k views Asked by At

I am reading data from a table using textscan(). The table has 90 columns and I want to read each column's values as a floating-point number. Looking at the documentation, I have to use specifier %f - but it seems I need to use it 90 times, so I end up with this:

c = textscan(fid,'%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f
                  %f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f
                  %f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f
                  %f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f');

which basically works, but I am wondering whether there is some way around to avoid typing specifier for every column I have in my table.

4

There are 4 answers

0
Andrew Janke On BEST ANSWER

Use repmat to build your format string based on the number of columns.

nCols = 60;
format = repmat('%f', [1 nCols]);
c = textscan(fid, format);

This is flexible enough to use if you had e.g. a couple string columns mixed in.

nNumberCols = 58;
format = ['%s%s' repmat('%f', [1 nNumberCols])];
c = textscan(fid, format);
2
Aabaz On

For a very simple ASCII file composed of 90 columns of floating point numbers separated by a known delimiter, maybe it would be simpler to use the Matlab function dlmread.

For example if your file rand.txt is:

0.8147    0.0975    0.1576    0.1419    0.6557
0.9058    0.2785    0.9706    0.4218    0.0357
0.1270    0.5469    0.9572    0.9157    0.8491
0.9134    0.9575    0.4854    0.7922    0.9340
0.6324    0.9649    0.8003    0.9595    0.6787

You can use: randmat=dlmread('rand.txt');

0
Oli On

You can just do a textscan with only one "%f" and then reshape it as you want or converting it to cell as you want:

fid=fopen('bla.txt','r');
M=textscan(fid,'%f')
M=reshape(M{1},[],5)
M=num2cell(M,1)
fclose(fid);
1
Sunny Manchanda On

I would suggest use:

fileId=fopen('fileloc.txt');
formatSpec='%f';
N=90;
data=textscan(fileId,formatSpec,N);