Using the link provided in @Bee answer and some tinkering the problem is solved like this:
aviobj=VideoWriter(filename);
open(aviobj);
hFig=figure('Visible','Off');
for loop comes here
cla
%All Drawing stuff
img = hardcopy(hFig, '-dzbuffer', '-r0');
writeVideo(aviobj, im2frame(img));
end
close(aviobj)
Note that it is using the VideoWriter
instead of deprecated avifile
and addframe
and it does the rendering in memory not on disk so it's reasonably fast.