Why does MATLAB slow down when printing lots of (.png) figures?

Go To StackoverFlow.com

5

I am printing a large series of figures as .png files. Each figure is a plot of a column from a data matrix, and I take the .png files and string them together into an animation.

My problem is that the first few hundred images print quickly, but the amount of time to create each new figure increases rapidly, from ~0.2 sec for the first few hundred .png files to 2 sec or more at around the 800th figure.

Memory usage increases during the run of the script, but only by 1MB every few seconds or so. This is on Windows running R2009b 64-bit.

My code looks something like:

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
2012-04-05 16:10
by andyras
can you do only 500 at a time? have a service that will restart your app - l--''''''---------'''''''''''' 2012-04-05 16:12
I can't stress this enough... MATLAB has a wonderful profiler built in and you should use it regularly. Profiling helps to identify many of this issues - linuxuser27 2012-04-05 17:39


4

Try not to regenerate the plot, but only change the XData and YData properties at each iteration:

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

Another suggestion. If you want to create an animation, why are you generating png files? Use GETFRAME and make a MOVIE directly in MATLAB.

2012-04-05 16:57
by yuk


2

This seems like a memory leak. You may be able to help Matlab release the leaked memory by creating and closing each figure in the loop.

for i = 1:n
    f = figure;
    % plot
    % print
    close(f)
end

Update: Here's a question and answer saying that this technique works.

2013-09-06 15:42
by shoelzer
Didn't try, but if closing an image and making a new one takes some time, consider only doing it every 100 images or so - Dennis Jaheruddin 2013-09-06 16:10
Ads