MATLAB: How to speed up an animation plot

3d plotanimated plotdrawnowinterpolationmoviepausesurfsurf plot

I don't know if this a little extreme but I need to plot 480 plots. I'm combining them in an animated plot so I can see how the plot fluctuates over time. However, it's taking an unbelievably long time (timed it and it took almost 37 minutes) to get through all 480 plots. The transitions aren't smooth and are very laggy. It also makes my computer lag. This is the code I have. Can't seem to figure out the problem. Should I make changes to it or turn this animated plot into a movie instead? If yes, how do I do so? Thanks in advance!
hold on;
for k = 1:(length(h)*added_points)
for i = 1:30
for j = 1:30
vqVal = zeros(1,1);
if ~isempty(cellArray{i,j})
% new cell array
vqVal = cellArray{i,j}(k);
vqHrPax{i,j} = vqVal;
h = linspace(103.6,104,30);
y = linspace(1.5,1.25,30);
[X,Y] = meshgrid(h,y);
V = cell2mat(vqHrPax);
n = 300;
xq = linspace(103.6,104,n);
xy = linspace(1.5,1.25,n);
[Xq,Yq] = meshgrid(xq,xy);
Vq = interp2(X,Y,V,Xq,Yq,'cubic');
surf(Xq,Yq,Vq); % plots interpolated data
% for loop to change title of each plot
xlabel('Longitude'); ylabel('Latitude');
% str = sprintf('Pax at Hour %d', k);
% title(str)
s = 0;
for l = s:(s+20)
if k > s && k <=(s+20)
str = sprintf('Hour %d', ((s/20)+1));
s = s + 20;
axis tight
colormap default
% pause(0.001)

Best Answer

Use the profiler to find the bottleneck of the code. It is not worth to improve a part, which takes 1% of the runtime, because an (impossible) infinite acceleration would reduce the runtime by 1% only.
Move repeated operations out of the loop, e.g.:
h = linspace(103.6,104,30);
y = linspace(1.5,1.25,30);
[X,Y] = meshgrid(h,y);
Replace the loops of i and j by:
V = zeros(30, 30);
for iC = 1:900
if ~isempty(cellArray{i,j})
V(iC) = cellArray{i,j}(k);
But the main problem is (most likely - I cannot run your code) that a huge bunch of SURF objects is created. Prefer to create one object only and adjust its values. Define "hSurf = []" before the loops. Then:
% Replace:
% surf(Xq,Yq,Vq); % plots interpolated data
% By:
if isempty(hSurf)
hSurf = surf(Xq,Yq,Vq); % plots interpolated data
set(hSirf, 'XData', Xq, 'YData', Yq, 'ZData', Vq);
Matlab's 1D interpolation is really lame. I don't know if this matters interp2 also. But if it does, think of replacing it by a handmade function. X,Y,Xq and Vq are constant in your problem. This should be useful for creating a faster version.
For more details it would be useful if you provide input data. It is hard to guess, where improvements of the code are useful, without running the code. It is like repairing a car without starting the engine.