Avoid entering a conversion specifier for each column in the 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 value as a floating point number. If you look at the documentation, I should use the %f specifier - but it seems to me that I need to use it 90 times, so I get the following:

 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 if there is a way to avoid entering a qualifier for each column that I have in my table.

+7
source share
4 answers

Use repmat to create a format string based on the number of columns.

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

It is flexible enough to use if you have, for example, multiple row columns mixed.

 nNumberCols = 58; format = ['%s%s' repmat('%f', [1 nNumberCols])]; c = textscan(fid, format); 
+11
source

For a very simple ASCII file consisting of 90 columns of floating point numbers separated by a well-known separator, it might be easier to use the Matlab dlmread function.

For example, if your rand.txt file 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');

+3
source

You can just make textscan with just one "% f" and then change it as you wish or convert it to a cell as you want:

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

I would suggest using:

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

All Articles