9

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.

Amro
  • 123,847
  • 25
  • 243
  • 454
Geek On Acid
  • 6,330
  • 4
  • 44
  • 64

4 Answers4

12

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);
Andrew Janke
  • 23,508
  • 5
  • 56
  • 85
3

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

Aabaz
  • 3,106
  • 2
  • 21
  • 26
  • Hmm but this solution reads data into a matrix, while I need to read it into a cell array and also using `fid` identifier (which `textscan` does). – Geek On Acid Jan 10 '12 at 15:50
  • You can convert a matrix to a cell array via the function [mat2cell](http://www.mathworks.fr/help/techdoc/ref/mat2cell.html). As for the file identifier, it is often the case that the filename is also available, if it is not in the context of your problem then Andrew Janke and Oli's answers will work just fine. This is just an alternative. – Aabaz Jan 10 '12 at 16:23
2

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);
Oli
  • 15,935
  • 7
  • 50
  • 66
1

I would suggest use:

fileId=fopen('fileloc.txt');
formatSpec='%f';
N=90;
data=textscan(fileId,formatSpec,N);
  • This code will only read in the first line. You would need to looped it to read in all lines of the file. – goryh Oct 02 '17 at 12:20