MATLAB: Make 2 videos side by side

MATLABvideo on matlab

i have the following code to make 2 videos side by side.
v1 = VideoReader('XXXXXXX.avi')
v2 = VideoReader('XXXXXXX.avi')
i1 = 0;
i2 = 0;
while i1 < v1.NumberOfFrames && i2 < v2.NumberOfFrames
if i1 < v1.NumberOfFrames
i1 = i1+1;
subplot(2,2,1)
image(v1.read(i1))
end
if i2 < v2.NumberOfFrames
i2 = i2+1;
subplot(2,2,2)
image(v2.read(i2))
end
drawnow
end
but a figure will keep popping out whenever i try to close the window. the window will only close until the video ends. how to fix that? i will also get an error saying :
Error using VideoReader/read (line 160)
The frame index requested is beyond the end of the file.
how to fix both things? please help.

Best Answer

v1 = VideoReader('XXXXXXX.avi')
v2 = VideoReader('XXXXXXX.avi')
i1 = 0;
i2 = 0;
fig = gcf;
ax1 = subplot(2,2,1, 'Parent', fig);
ax2 = subplot(2,2,2, 'Parent', fig);
while i1 < v1.NumberOfFrames && i2 < v2.NumberOfFrames
if i1 < v1.NumberOfFrames
i1 = i1+1;
if ishandle(ax1)
image(ax1, v1.read(i1));
else
break; %axes is gone, figure is probably gone too

end
end
if i2 < v2.NumberOfFrames
i2 = i2+1;
if ishandle(ax2)
image(ax2, v2.read(i2));
else
break; %axes is gone, figure is probably gone too
end
end
drawnow
end
Note: in R2014b or later, it would be better to use isgraphics() instead of ishandle()
Related Question