matlabvideomovie

How to code an inner loop to get only non-empty movie frames in Matlab?


In my plotting code, I'm using a for loop

frame(S) = struct('cdata',[],'colormap',[]);    % pre-allocate frames structure

for i = 1 : round(N/S) : N

some plotting code..

axis equal 

drawnow;

frame(i) = getframe();

end

and then using VideoWriter:

video = VideoWriter('My_movie.avi', 'Uncompressed AVI');

video.FrameRate = 60;

open(video)

writeVideo(video, frame);

hold off 

close(video);

But I'm getting the error

The 'cdata' field of FRAME must not be empty.

I know what the issue is but am not sure how to resolve it.

The values for i are 1,5,9,13...

which means that frames 2,3,4,6,7,8,10,11,12, etc would be empty.

I think I need an inner loop, just before I call the getframe() function but am not sure how to do so properly and perhaps iterate over the index.

Currently, I have tried coding this inner loop:

for j = 1:S

frame(j) = getframe();

end

However, the simulation is now running extremely slow because of this inner loop.


Solution

  • The way you code your loop, you are not assigning data to each frame. You pre-allocate S frames (frame numbers 1 through S), but then assign data to S frames with indices 1 through N (N>S). This makes no sense to me.

    But it seems that you use i also to draw your animation, where you do want to skip "frames".

    The way to do so properly is like this:

    frame(S) = struct('cdata',[],'colormap',[]);    % pre-allocate frames structure
    for j = 1:S
       i = j * round(N/S);
       % some plotting code..
       axis equal 
       drawnow;
       frame(j) = getframe();
    end
    

    Here, each frame in the range 1:S is assigned data, but i still skips values like it does in your code.