首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Matlab:多行(%d %d %ld)文件的快速读取

Matlab:多行(%d %d %ld)文件的快速读取
EN

Stack Overflow用户
提问于 2014-12-21 22:09:16
回答 2查看 267关注 0票数 1

我对fscanf及其在使用结构化数据读取文件时的时间性能感到沮丧。我想要读取一个.txt文件,它每行有三个条目: DOUBLE DOUBLE LONG-DOUBLE,我只想读取第一个N个条目。不幸的是,fscanf非常慢。你知道更快的方法吗?

顺便说一句,我在这里知道关于这个主题的几个主题,例如this question。但是,这个答案对我的情况没有帮助,因为我已经在使用fscanf了。

我的代码是:

代码语言:javascript
复制
    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文件如下所示:

代码语言:javascript
复制
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的AspaceBspaceC是0,9,C是64位整数

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-12-22 04:37:18

您可以在这里使用textscan来读取第一个N条目,在最新版本的MATLAB中,这被认为是相当快的。

代码语言:javascript
复制
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};
票数 2
EN

Stack Overflow用户

发布于 2014-12-21 23:26:36

代码语言:javascript
复制
% 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]);

默认情况下,它将被读为双倍。

获得整数值

代码语言:javascript
复制
A = uint8(T(:,1));
B = uint8(T(:,2));
C = uint64(T(:,3));

希望这会有所帮助:)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27594305

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档