在MATLAB中以矩阵形式加载文本文件

2024-06-12 17:11:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文本文件,它是一个巨大的数据集(约9gb)。我已经将文件安排为244x3089987,数据用制表符分隔。我想在Matlab中加载这个文本文件作为一个矩阵。这是我尝试过的,但没有成功(我的Matlab被挂起)。在

fread = fopen('merge.txt','r');

formatString = repmat('%f',244,3089987);

C = textscan(fread,formatString);

我是做错了什么还是我的方法错了?如果这在Python中很容易实现,请有人提出相应的建议。在


Tags: 文件数据方法txt矩阵merge建议制表符
3条回答

如果您阅读^{}的文档,您将看到您可以定义一个输入参数N,以便:

textscan reads file data using the formatSpec N times, where N is a positive integer. To read additional data from the file after N cycles, call textscan again using the original fileID. If you resume a text scan of a file by calling textscan with the same file identifier (fileID), then textscan automatically resumes reading at the point where it terminated the last read.

您还可以将一个空白的formatSpec传递给textscan,以便读取任意数量的列。这就是^{},即textscan的包装器的操作方式。在

例如:

fID = fopen('test.txt');
chunksize = 10; % Number of lines to read for each iteration
while ~feof(fID) % Iterate until we reach the end of the file
    datachunk = textscan(fID, '', chunksize, 'Delimiter', '\t', 'CollectOutput', true);
    datachunk = datachunk{1}; % Pull data out of cell array. Can take time for large arrays
    % Do calculations
end
fclose(fID);

这将读取10行块,直到您到达文件的末尾。在

如果您有足够的RAM来存储数据(一个244 x 3089987数组double刚好超过6 Gig),那么您可以:

^{pr2}$

在最近的MATLAB版本中,另一个选项是使用datastore。这样做的好处是允许你翻页浏览数据,而不是一次读取全部数据。它通常可以推断出所有格式化的东西。在

http://www.mathworks.com/help/matlab/import_export/read-and-analyze-data-in-a-tabulartextdatastore.html

尝试: A = importdata('merge.txt', '\t');

http://es.mathworks.com/help/matlab/ref/importdata.html

如果行不是由'\n'分隔: [C, remaining] = vec2mat(A, 244)

http://es.mathworks.com/help/comm/ref/vec2mat.html

相关问题 更多 >