MATLAB: How to create an animated plot

3d plotanimated plotplotsurf

I'm trying to combine 24 plots (each plot representing the density of people in a certain area) into one figure (making some what of an animated plot). But instead of my 24 plots being displayed one after the other in the same figure with a short pause in between each one, I end up with 24 separate figures. How do I combine them and make an animated plot? This is the code I have at the moment. Trying to combine them so I can see how density changes after every hour.
for k = 1:24
for i = 1:30
for j = 1:30
hrVal = zeros(1,1);
if ~isempty(gridPax{i,j})
hrVal = log(gridPax{i,j}(k)+1);
end
hrPax{i,j} = hrVal;
end
end
x = linspace(103.6,104,30);
y = linspace(1.5,1.25,30);
[X,Y] = meshgrid(x,y);
Z = cell2mat(hrPax);
% interpolate to a finer grid
newG = 200;
xq = linspace(103.6,104,newG);
xy = linspace(1.5,1.25,newG);
[Xq,Yq] = meshgrid(xq,xy);
Zq = interp2(X,Y,Z,Xq,Yq,'cubic');
figure('Name', 'Pax per Hour');
hold on;
surf(Xq,Yq,Zq);
xlabel 'Latitude'; ylabel 'Longitude'; zlabel 'No. of Pax';
axis tight
colormap default
end

Best Answer

You place figure and hold on line outside the loop:
figure('Name', 'Pax per Hour');
hold on;
for k = 1:24
for i = 1:30
for j = 1:30
hrVal = zeros(1,1);
if ~isempty(gridPax{i,j})
hrVal = log(gridPax{i,j}(k)+1);
end
hrPax{i,j} = hrVal;
end
end
x = linspace(103.6,104,30);
y = linspace(1.5,1.25,30);
[X,Y] = meshgrid(x,y);
Z = cell2mat(hrPax);
% interpolate to a finer grid
newG = 200;
xq = linspace(103.6,104,newG);
xy = linspace(1.5,1.25,newG);
[Xq,Yq] = meshgrid(xq,xy);
Zq = interp2(X,Y,Z,Xq,Yq,'cubic');
surf(Xq,Yq,Zq);
xlabel 'Latitude'; ylabel 'Longitude'; zlabel 'No. of Pax';
axis tight
colormap default
drawnow
end
Related Question