# How to create animation of multiple of frames using for loop ?

27 views (last 30 days)
Jamie Al on 17 Oct 2021
Commented: the cyclist on 17 Oct 2021
I have the following code that plots text file data. However, here I chose few text files to represent and plot. I would like to plot all the data files and combine them as an animation something like a for loop that loops over all my data.
My current code:
% Frame to plot
frame =[18 17 18]; % this is the number of frames (text files) inside each folder (different values of w)
% I have a total of 22 text files in each folder that I wanna loop over and
% make an animation
xStart = [257 257 285]; %257; %[257 257 285]; %230;
xEnd = 340*[1 1 1]; %340; %340*[1 1 1]; %380;
% Get the range in x of the values we want to consider
% Load X and Y data
XX = load([upperDir subDir{1} 'X.txt']);
YY = load([upperDir subDir{1} 'Y.txt']);
% Make the Fourier mesh
n = size(XX);
dx = XX(2,1) - XX(1,1);
dy = YY(1,2) - YY(1,1);
L(1) = max(max(XX)) + dx;
L(2) = max(max(YY)) + dy;
% Make a vector for x direction
xVec = XX(:,1);
yVec = YY(1,:)';
% Make a vector for ky
kyVec = makeK(L(2), n(2))*1000;
kyVec = kyVec(1:n(2)/2);
maxkx = 0;
minkx = 1e11;
fontSize = 16;
w = [305 175 125];
kx = linspace(minkx, maxkx, 1000);
ky = linspace(kyVec(2), kyVec(end), 1000);
for i = 3:-1:1 % this for loop represnts the three different folders that I am taking the text files from to plot
% Make a vector for kx
kxVec = makeK( xVec(xEnd(i)) - xVec(xStart(i)) + dx, 2^(nextpow2(xEnd(i) - xStart(i) +1)))*1000;
kxVec = kxVec(1:length(kxVec)/2);
maxkx = max([ maxkx kxVec(end)]);
minkx = min([ minkx kxVec(2)]);
% Load density data
ne_bg = load([upperDir subDir{i} 'ne_unpert.txt']);
ne = load([upperDir subDir{i} 'ne' num2str(frame(i)) '.txt']);
ne_p = ne - ne_bg ;
phi_bg = load([upperDir 'phi_unpert.txt']);
phi = load([upperDir subDir{i} 'phi' num2str(frame(i)) '.txt']);
phi_p = phi - phi_bg ;
dn_over_n = ne_p ./ ne;
% % Take fft in x direction and integrate in y direction to get spectrum
dn_spectrum_x = FFTmat(dn_over_n(xStart(i):xEnd(i), :), yVec, 2, 1)';
phi_spectrum_x = FFTmat(phi_p(xStart(i):xEnd(i), :), yVec, 2, 1)';
% % Take fft in y direction and integrate in x direction to get spectrum
dn_spectrum_y = FFTmat(dn_over_n(xStart(i):xEnd(i), :), xVec(xStart(i):xEnd(i)), 1, 1)';
phi_spectrum_y = FFTmat(phi_p(xStart(i):xEnd(i), :), xVec(xStart(i):xEnd(i)), 1, 1)';
subplot(1,2,1);
loglog(kyVec(2:end), dn_spectrum_y(2:end),'-','LineWidth',1,'DisplayName',['w = ' num2str(w(i)) ' km']);
gird on;
subplot(1,2,2);
loglog(kyVec(2:end), phi_spectrum_y(2:end),'-','LineWidth',1,'DisplayName',['w = ' num2str(w(i)) ' km']);
grid on;
end

the cyclist on 17 Oct 2021
I believe you can do what you want by using the getframe and movie functions.
##### 2 CommentsShowHide 1 older comment
the cyclist on 17 Oct 2021
There are examples in the documenation pages I cited.
You can also find other examples online if you search for keywords like "example matlab movie".