如何编写内部循环以在 Matlab 中仅获取非空电影帧?

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

在我的绘图代码中,我使用了 for 循环

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

然后使用VideoWriter:

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

video.FrameRate = 60;

open(video)

writeVideo(video, frame);

hold off 

close(video);

但我收到错误

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

我知道问题出在哪里,但不确定如何解决。

i 的值为 1,5,9,13...

这意味着帧 2、3、4、6、7、8、10、11、12 等将是空的。

我想我需要一个内部循环,就在我调用 getframe() 函数之前,但我不确定如何正确地执行此操作以及可能遍历索引。

目前,我已经尝试编写这个内部循环:

for j = 1:S

frame(j) = getframe();

end

但是,由于这个内部循环,现在模拟 运行 非常慢。

您编写循环代码的方式并没有为每一帧分配数据。您预先分配 S 帧(帧编号 1S),然后将数据分配给索引为 1NS 帧(N>S)。这对我来说毫无意义。

但您似乎也使用 i 来绘制动画,您确实想跳过 "frames"。

正确的做法是这样的:

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

这里,1:S 范围内的每一帧都分配了数据,但 i 仍然像在您的代码中那样跳过值。