Search code examples
matlabanimationvideomatlab-figure

Although I used 'drawnow' and 'hold on', last plot still appears in animation - MATLAB


I read a lot of answers here, but for some reason my animation still doesn't work as expected.

The axis range should vary from frame to frame. The 'Hurricane Center' caption should remain in the center all the time, but the captions from the previous frames must be erased. Also, I'm afraid that some of the data from previous parts remain.

I used hold on and draw now but it still happens.


The animation can be seen here:

image


Code:

v = VideoWriter('test_video.avi');
v.FrameRate = 4;
v.open()   

hold on
for i=1:length(relevant(1,1,:))      
    if isempty(relevant) == 0     
        title('Lightning around Hurricane Jerry')
        grid on  

        ylim([Interp_Jerry(i,2)-Radius Interp_Jerry(i,2)+Radius])
        xlim([Interp_Jerry(i,3)-Radius Interp_Jerry(i,3)+Radius])

        ylabel('latitude')
        xlabel('longitude')

        text(Interp_Jerry(i,3),Interp_Jerry(i,2),txt1); 

        scatter(relevant(:,3,i),relevant(:,2,i),'.');
        drawnow
        pause(0.1);  

        v.writeVideo(getframe(fig));
    end
end  
v.close()

Solution

  • The best of the two worlds:

    v = VideoWriter('test_video.avi');
    v.FrameRate = 4;
    v.open()   
    
    hold on;
    for i=1:length(relevant(1,1,:))      
        if ~isempty(relevant)  % Corrected     
    
            if i == 1
                % Prepare first plot and save handles of graphical objects
                ht = text(Interp_Jerry(i,3),Interp_Jerry(i,2),txt1); 
                hold on;
                hs = scatter(relevant(:,3,i),relevant(:,2,i),'.');
    
                ylabel('latitude')
                xlabel('longitude')
                title('Lightning around Hurricane Jerry')
                grid on  
            else
                % Update graphical objects
                set(ht, 'position', [Interp_Jerry(i,3), Interp_Jerry(i,2)]);
                set(hs, 'XData', relevant(:,3,i) , 'YData' , relevant(:,2,i));
            end
    
            ylim([Interp_Jerry(i,2)-Radius Interp_Jerry(i,2)+Radius])
            xlim([Interp_Jerry(i,3)-Radius Interp_Jerry(i,3)+Radius])
    
            drawnow
            pause(0.1);  
    
            v.writeVideo(getframe(fig));
        end
    end  
    v.close()