MATLAB: How to crate a video of multiple surf plots

plotsurfvideo

I am running a code which produces a surf plot for every step of the loop. I want to create a video of the all these surf plots produced in each step. How can I do that?

Best Answer

h = figure;
axis tight manual % this ensures that getframe() returns a consistent size
filename = 'test.gif';
[X,Y,Z] = peaks(100) ;
for n = 1:50
% Draw plot for y = x.^n
surf(X,Y,randsample(10,1)*Z) ;
zlim([-100 100])
shading interp
drawnow
% Capture the plot as an image
frame = getframe(h);
im = frame2im(frame);
[imind,cm] = rgb2ind(im,256);
% Write to the GIF File
if n == 1
imwrite(imind,cm,filename,'gif', 'Loopcount',inf);
else
imwrite(imind,cm,filename,'gif','WriteMode','append');
end
end