Suicide Bunny
Suicide Bunny

Reputation: 938

How to avoid the repeated paragraghs of long txt files being ignored for importdata in matlab

I am trying to import all double from a txt file, which has this form

#25x1 string

#9999x2 double
.
.
.

#(repeat ten times)

However, when I am trying to use import Wizard, only the first

25x1 string
9999x2 double.

was successfully loaded, the other 9 were simply ignored

How may I import all the data? (Does importdata has a maximum length or something?) Thanks

Upvotes: 0

Views: 37

Answers (1)

nkjt
nkjt

Reputation: 7817

It's nothing to do with maximum length, importdata is just not set up for the sort of data file you describe. From the help file:

For ASCII files and spreadsheets, importdata expects to find numeric data in a rectangular form (that is, like a matrix). Text headers can appear above or to the left of the numeric data, as follows:

Column headers or file description text at the top of the file, above the numeric data. Row headers to the left of the numeric data.

So what is happening is that the first section of your file, which does match the format importdata expects, is being read, and the rest ignored. Instead of importdata, you'll need to use textscan, in particular, this style:

C = textscan(fileID,formatSpec,N)

fileID is returned from fopen. formatspec tells textscan what to expect, and N how many times to repeat it. As long as fileID remains open, repeated calls to textscan continue to read the file from wherever the last read action stopped - rather than going back to the start of the file. So we can do this:

fileID = fopen('myfile.txt');
repeats = 10;

for n = 1:repeats

    % read one string, 25 times
    C{n,1} = textscan(fileID,'%s',25); 
    % read two floats, 9999 times
    C{n,2} = textscan(fileID,'%f %f',9999);

end

You can then extract your numerical data out of the cell array (if you need it in one block you may want to try using 'CollectOutput',1 as an option).

Upvotes: 2

Related Questions