使用 matfile() 将数据附加到已保存的变量

Append data to a saved variable using matfile()

我有一些随机的 2D 数据 fuffa 我保存到一个文件 fuffalo:

fuffa=rand(10,10);
save('fuffalo','fuffa', '-v7.3')

然后我通过一个循环生成其他 fuffa 数据,我想将这些数据(在第三维中)附加到保存的变量。为此,我尝试应用 this 建议:

m1 = matfile('fuffalo.mat', 'Writable', true);

for ii=1:3
   fuffa2=rand(10,10);    
   m1.fuffa(1:10,1:10,end+1)=fuffa2;
end

但是,在 ii=2 我收到以下错误:

Variable 'fuffa' has 2 dimensions in the file, this does not match the 3 dimensions in the indexing subscripts.

如何说服 MATLAB 在三维中追加?

因为您访问的是磁盘上的文件,而不是工作区变量,所以您可能会遇到扩展维数的问题。你不会有这个问题处理存储在内存中的变量(比如如果你使用 load 而不是 matfile)。

要避免这种情况,最好的方法是 pre-allocation。我将假设这是对您的实际问题的简化,并且您需要能够对潜在的 2D 数组进行此类 3D 扩展。

在这种情况下,只需使用 cat 在第 3 维中连接:

fuffa=rand(10,10);
save('fuffalo','fuffa', '-v7.3')
m1 = matfile('fuffalo.mat', 'Writable', true);
for ii=1:3
    fuffa2=rand(10,10);
    % Concatenating in the 3rd dimension, avoiding used 'end' which 
    % assumes that dimension already exists
    m1.fuffa=cat(3,m1.fuffa,fuffa2);
end
% m1.fuffa <10x10x4 double>

请注意,通过这样做,您会将整个 .mat 数据带入内存以进行串联,从而破坏了 matfile() 的要点。但是,您以前的方法会面临同样的问题,因为在 docs 中我们看到:

Using the end keyword as part of an index causes MATLAB to load the entire variable into memory.

如前所述,预分配可能会更好!