在 MATLAB 中将文本文件作为矩阵加载

Load Text File as a matrix in MATLAB

我有一个文本文件,它包含大量数据(大约 9 GB)。我将文件安排为 244 X 3089987,数据以制表符分隔。我想将这个文本文件作为矩阵加载到 Matlab 中。这是我尝试过但没有成功的方法(我的 Matlab 被挂起)。

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

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

C = textscan(fread,formatString);

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

尝试: 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

如果您阅读 textscan 的文档,您会发现您可以定义一个输入参数 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 以读取任意数量的列。 dlmreadtextscan 的包装器就是这样运作的。

例如:

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 来存储数据(double244 x 3089987 数组刚刚超过 6 GB)那么您可以这样做:

mydata = textscan(fID, '', 'Delimiter', '\t', 'CollectOutput', true);
mydata = mydata{1}; % Pull data out of cell array. Can take time for large arrays

我很惊讶这甚至在尝试 运行,当我尝试类似的 textscan 时会抛出错误。

如果您真的想使用 textscan,您只需要每一行的格式,这样您就可以将代码中的 244 替换为 1,它应该可以工作。编辑:阅读您的评论后,第一个元素不是列数,因此您应该 formatString = repmat('%f',1, 244);。此外,您显然可以将格式保留为空 (''),它会起作用。

但是,Matlab 有几个 text import functions 其中文本扫描很少是最简单的方法。

在这种情况下,我可能会使用 dlmread,它可以处理任何分隔的数字数据。你想要这样的东西:

C=dlmread('merge.txt', '\t');

此外,当您尝试加载 9GB 的数据时,我假设您有足够的内存,如果没有,您可能会遇到内存不足的错误,但这是需要考虑的事情。

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

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