如何附加多个具有相同变量名的 .mat 文件?

How to append multiple .mat files that have the same variable names in them?

我 运行 我的脚本会生成成百上千个 .mat 文件。每个文件都包含两个变量:resultsU 和 resultsT。我想附加文件但不覆盖变量。在 Matlab 中最简单的方法是什么?有些人建议手动操作 .mat 文件,当您有数百个 .mat 文件时,这并不容易或高效。

实际上比您想象的要容易得多。如果要附加到 MAT 文件,只需使用 save-append 标志。假设您有几个变量...让我们称它们为 pq,并假设您有一个名为 test.mat 的文件,它非常简单:

save('test.mat','p','q','-append');

这样做的好处是您不需要加载 MAT 文件中的任何变量并使用附加变量重新保存它们。这会将所需的变量附加到 MAT 文件中,而无需将它们加载到 MATLAB 中。

如果目录中有一堆 .mat 个文件,您可以这样做:

folder = '...'; %// Place directory here
f = dir(folder); %// Find files

%// For each file...
for idx = 1 : numel(f)
    name = fullfile(folder, f(idx).name); %// Get path to file

    %// Do some processing
    %//...
    %//

    %// Append to file
    save(name, ..., ..., ..., ..., '-append');
end

save... 中的内容是您要附加到每个文件的变量。

is good if running the code which created the files is an option. However, if working with a huge amount of files is a given fact which you need to deal with, I would suggest to go about this using and array of structs (which resembles struct concatenation)。

考虑以下示例函数:

function combined_results = CombineMat(newFolder)

oldFolder = cd; %// Backup the current directory
cd(newFolder);  %// Switch to some new folder
fList = dir('*.mat'); fList = {fList.name}'; %'// Get the file list

%% // Processing the list of files:
if isempty(fList), combined_results = []; return, end %// Check that some files exist

%// Initialize the result struct by loading the last file (also preallocates the struct):
nFiles = size(fList,1);
combined_results(nFiles) = load(fullfile(newFolder,fList{1}));

%// See if there is only 1 file, and return if so:
if nFiles == 1, return, end

%// Process any additional files 
for ind1 = 1:nFiles-1
    combined_results(ind1) = load(fullfile(newFolder,fList{ind1}));
end

%% Cleanup - changing the current directory back:
cd(oldFolder);

它的作用是合并 .mat 个包含相同变量名的文件。现在你可以 运行 combined_results = CombineMat(folder_with_mat_files) 并得到一个 struct 其中包含所有不同的结果(假设你有足够的内存来保存它们)。将此 struct 存入内存后,您可以将其保存到单个 .mat 文件中。

注意1:如果你没有足够的内存来加载所有文件,你可以在CombineMat中添加另一段代码,将combined_results转储到磁盘并在一定时间后清除它循环迭代次数(可能使用 rayryeng 建议的 '-append' 选项。如果 OOM 发生,这对我个人来说没有意义,因为那样你会加载生成的文件时遇到问题:)

注2:显然,如果您希望结果不是structs的数组,则需要相应地修改代码。


在更一般的情况下,当您尝试连接具有不同变量名称的结构时,您可以使用 following FEX submission(我可以根据个人经验推荐!)。


P.S. 我的代码是在 MATLAB 2015a 上写的。