我对fscanf
及其在阅读带结构化数据的文件中的时间表现感到沮丧。我想读一个.txt文件,每行有三个条目:DOUBLE DOUBLE LONG-DOUBLE,我只想读取前N个条目。不幸的是,fscanf
非常缓慢。你知道更快的方法吗?
顺便说一下,我知道这个主题有几个主题,例如this question。但是,答案在我的案例中没有用,因为我已经在使用fscanf
。
我的代码是:
formatSpec='%d %d %ld'; % important: last one is long-double to support 64bit values!
sizeA=[3 100000];
file1=fopen('file1.txt','r');
[content,cc]=fscanf(file1,formatSpec,sizeA);
fclose(file1);
您是否知道更难以阅读具有给定结构的N行文件?谢谢!
修改:file1.txt
的文件内容如下所示:
1 1 204378259709308
0 1 204378259782523
1 1 204378260105693
3 1 204378260381676
3 1 204378260854931
1 1 204378261349990
1 1 204378262189528
0 1 204378263067715
1 1 204378263301204
1 1 204378263676471
1 1 204378263771064
1 1 204378264565420
0 1 204378264608240
0 1 204378264973698
...
3 1 205260543966542
基本上: A [空间] [空间] B [空间]Ç A和B为[0,9],C为64位整数
答案 0 :(得分:2)
您可以在此处使用 textscan
来阅读第一个N
条目,这在最新版本的MATLAB中可能相当快 -
fid = fopen(inputfile); %// inputfile is the path to the input text file
C = textscan(fid, '%d %d %d64',N); %// N is the number of first entries to be read
fclose(fid);
%// Get data into three separate variables (if needed)
col1 = C{:,1};
col2 = C{:,2};
col3 = C{:,3};
答案 1 :(得分:0)
% To read all the rows and columns
T = dlmread('file1.txt',' ');
% To read specific rows and columns
% R1 - First row to read
% C1 - First column to read
% R2 - First row to read
% C2 - First column to read
% First row or column index is 0
% Following is the code to read rows 3, 4 and 5
T = dlmread('file1.txt',' ',[2 0 4 2]);
默认情况下,它将显示为double。
获取整数值
A = uint8(T(:,1));
B = uint8(T(:,2));
C = uint64(T(:,3));
希望这会有所帮助:)