Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 942
Geek On Acid Avatar asked Jan 10 '12 15:01

Geek On Acid


3 Answers

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);
like image 76
Andrew Janke Avatar answered Nov 15 '22 08:11

Andrew Janke


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');

like image 38
Aabaz Avatar answered Nov 15 '22 06:11

Aabaz


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);
like image 26
Oli Avatar answered Nov 15 '22 06:11

Oli