Hi Richard,
The "shaking" or flickering observed when displaying video frames and plots in a MATLAB loop can happen because each call to ‘subplot’ , ‘imshow’ , or ‘imagesc’ inside the loop can recreate or resize axes, causing the display to jump or flicker.
To address this, create your figure and axes just once before the loop and then update only the image and plot data inside the loop. This approach keeps the figure layout stable and makes updates much smoother.
You can use the sample code below to organize your code for flicker-free animation.
% Example parameters
NumberOfFrames = 100;
video_fps = 10;
FrameSize = [240, 320, 3]; % Example frame size
Frame_Binary_Size = [240, 320];
% Simulate particle counts and frames for demonstration
particles = randi([0 50], NumberOfFrames, 1);
videoFrames = uint8(randi([0 255], [FrameSize, NumberOfFrames]));
binaryFrames = randi([0 1], [Frame_Binary_Size, NumberOfFrames]);
% Create figure and axes once
figure;
ax1 = subplot(2,2,1);
hFrame = imshow(videoFrames(:,:,:,1), 'Parent', ax1);
title('Original Frame')
ax2 = subplot(2,2,2);
hBinary = imagesc(binaryFrames(:,:,1), 'Parent', ax2);
axis(ax2, 'image');
title('Detected Particles')
ax3 = subplot(2,2,[3 4]);
hPlot = plot(ax3, nan, nan, '-r');
axis([0 NumberOfFrames/video_fps 0 max(particles)+5])
title('Particle Counts')
xlabel('Seconds')
ylabel('Particle Count')
for ii = 1:NumberOfFrames
% Update images and plot data
set(hFrame, 'CData', videoFrames(:,:,:,ii));
set(hBinary, 'CData', binaryFrames(:,:,ii));
set(hPlot, 'XData', (1:ii)/video_fps, 'YData', particles(1:ii));
drawnow limitrate
end
The above code results in the following output:

For a better understanding of the above solution, refer to the following documentations:
