Mohammad Bazrafshan
Mohammad Bazrafshan

Reputation: 51

Animation of figure with subplots using VideoWriter in MATLAB

I'm trying to create an animation file in MATLAB from a figure with 2 subplots using the VideoWriter. However, the avi file that I get includes only one of the subplots.

Here is the code:

clc    
clear 
vidObj = VideoWriter('randdata');   
open(vidObj)    
figure (1)   
for i = 1:100       
    clf        
    subplot(1,2,1)        
    imagesc(rand(100))        
    subplot(1,2,2)        
    imagesc(rand(100))       
    drawnow       
    CF = getframe;        
    writeVideo(vidObj,CF);        
end

There must be something simple going wrong here but I don't know what. I would like to capture the entire figure.

Upvotes: 1

Views: 912

Answers (1)

Wolfie
Wolfie

Reputation: 30101

The documentation for getframe states in the first line:

F = getframe captures the current axes

So it's capturing the axes, not figure.

You want to use it as also specified in the documentation

F = getframe(fig) captures the figure identified by fig. Specify a figure if you want to capture the entire interior of the figure window, including the axes title, labels, and tick marks. The captured movie frame does not include the figure menu and tool bars.

So your code should be

clc; clear
vidObj = VideoWriter('randdata');
open(vidObj);
figure(1);
for ii = 1:100
    clf
    subplot(1,2,1)
    imagesc(rand(100))
    subplot(1,2,2)
    imagesc(rand(100))
    drawnow;
    % The gcf is key. You could have also used 'f = figure' earlier, and getframe(f)
    CF = getframe(gcf); 
    writeVideo(vidObj,CF);
end

For ease, you might want to just get a File Exchange function like the popular (and simple) gif to create an animated gif.

Upvotes: 3

Related Questions