How to prevent memory leak when using getframe? (edit: not memory leak)
Show older comments
Hi,
Edit: After communicating with Mathworks support we deduced that it was not a memory leak and it was expected behavior. Storing the large frames in a large matrix using a for loop eventually consumes a lot of RAM. By making the AVI file first and writing to it each iteration the code generates the same animation but primarily uses disk memory instead of RAM.
I am creating a script to simulate the motion of multiple particles in 2D space to test various algorithms for swarm control. As part of this simulation I would like to create a real-time animation of the particles.
Currently I am using 'getframe' and 'movie2avi' to accomplish this. The issue I am having is that 'getframe' causes a memory leak. Additionally the code I have runs very slow. As an example, I am using ode45 to solve the system model for 2 particles and when I let it choose the time-steps it creates 877 points for 5 seconds of data. This nearly maxed out my RAM. As soon as I cleared the movie variable from the workspace my RAM went back to normal levels. This will obviously become a serious problem when I start to simulate many more particles (I need to simulate at least 5 and I would like to reach 10-20).
So my question is: is there a way to prevent 'getframe' from eating all my RAM or is there another way I can generate the animation that is faster and more efficient with memory resources?
I have attached the segment of my code in question along with a .mat file with data to make it run (this is the data from the 5 second simulation I described). I left out the line that creates the AVI file b/c that doesn't cause any issues. The code is recreated here for ease.
Thanks,
John
load('TestData.mat');
figure;
set (gcf, 'Units', 'normalized', 'Position', [0,0.05,1,0.875]);
M(1:size(r1a,1)-1) = getframe(gcf);
for i=2:size(r1a,1);
% Find Delta Distance Vectors
dr1=r1a(i,:)-r1a(i-1,:);
dr2=r2a(i,:)-r2a(i-1,:);
% Plot Frenet-Serret Vectors
quiver(r1a(i-1,1),r1a(i-1,2),dr1(1),dr1(2),'Color','r','AutoScale', 'OFF','ShowArrowHead','OFF','Marker','.');
hold on
quiver(r2a(i-1,1),r2a(i-1,2),dr2(1),dr2(2),'Color','m','AutoScale', 'OFF','ShowArrowHead','OFF','Marker','.');
hold on
axis equal
grid on
% Build Movie
M(i-1) = getframe(gcf);
end
Accepted Answer
More Answers (1)
Image Analyst
on 8 Sep 2014
1 vote
Should your second "hold on" actually be a "hold off"? Sometimes I notice that if you keep piling stuff into the axes, it will accumulate them all, even though the underlying layers might not be seen. You might turn that last hold on into a hold off and put a "cla" or "cla reset" at the beginning of the loop to clear everything out.
Categories
Find more on Functions in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!