Slow import of text files

12 views
Skip to first unread message

cgb

unread,
Mar 9, 2009, 9:27:56 AM3/9/09
to Sysquake
I have space delimited text files in this format:
2009 02 09 00 00 27 1.2669 1.2702
2009 02 09 00 00 31 1.267 1.2702
2009 02 09 00 00 51 1.2668 1.2701
2009 02 09 00 00 56 1.2664 1.27
2009 02 09 00 00 59 1.2666 1.2701
They have many thousands of rows

So I wrote this function to import them into Sysqauke:
function m=txt2m(f)
m=[];
fd=fopen(f,'rt');
while feof(fd)==false
m=[m,fscanf(fd,'%f')];
end
fclose(fd);
m=m';

The problem is that it takes to long time to import them.
Is there any faster way of doing it?

/C-G

Yves Piguet

unread,
Mar 10, 2009, 2:51:02 PM3/10/09
to Sysquake
If you can, read the whole file as a string:

str = fread(fd, inf, '*char');

Replace linefeeds and carriage returns with spaces to make a single
line:

str(str == '\n' | str == '\r') = ' ';

And convert all numbers with a single call to sscanf:

m = sscanf(str, '%g');

Hth,

Yves
Reply all
Reply to author
Forward
0 new messages