and*_*ras 5 matlab memory-leaks
我正在打印一大堆数字作为.png文件.每个图都是数据矩阵中一列的图,我将.png文件和它们串在一起形成一个动画.
我的问题是前几百张图像打印速度很快,但创建每个新图形的时间会迅速增加,从前几百个.png文件的~0.2秒增加到大约800个图像的2秒或更多.
在脚本运行期间内存使用量会增加,但每隔几秒左右只会增加1MB.这是在Windows上运行R2009b 64位.
我的代码看起来像:
n = 1000;
matrix = rand(n);
f = figure('Visible','off'); % create the figure
for i_ =1:n
plot(1:n,matrix(:,i_));
ylim([0 1]);
set(f,'PaperUnits','inches','PaperPosition',[0 0 6 4]);
png_name = [ 'img/timestep_' sprintf('%05d',i_) ];
print('-dpng', png_name);
end
Run Code Online (Sandbox Code Playgroud)
尽量不要重新生成绘图,而只在每次迭代时更改XData和属性:YData
set(f,'PaperUnits','inches','PaperPosition',[0 0 6 4]);
h = plot(1, matrix(:,1));
ylim([0 1]);
for i_ = 1:n
set(h, 'XData', 1:n, 'YData', matrix(:,i_))
png_name = sprintf('img/timestep_%05d',i_);
print('-dpng', png_name);
end
Run Code Online (Sandbox Code Playgroud)
另一个建议。如果你想创建动画,为什么要生成 png 文件?使用GETFRAME直接在 MATLAB 中制作电影。