MATLAB: How to save matrices from specific points in a for loop

for loop

for n = 1:100
%first for loop for i = 2:end-1, second for loop for j = 2: end-1
for i = (2:Nx-1)
for j = (2:Ny-1)
%update equation
p_np1(i,j) = a^2 * (p_n(i+1,j) + p_n(i-1,j) ...
- 4*p_n(i,j) + p_n(i, j+1) + p_n(i, j-1)) ...
+ 2*p_n(i,j) - p_nm1(i,j);
end
end
% after each iteration, previous value becomes present
% pressure value
p_nm1 = p_n;
% after each iteration, present value becomes next pressure
% value
p_n = p_np1;
% Plotting continuous plot
% plot the field
imagesc(x_axis, y_axis, p_np1);
% set the limits on the y-axis, 'YDir' and 'normal' commands set the
% y-axis on the plot to go from low to high from bottom to top
set(gca, 'YDir', 'normal');
% adds title with the iteration number
title(['n = ' num2str(n)]);
% keeps updating plot
drawnow;
% briefly pause before continuing the loop
pause(0.1)
end
I want to save the arrays of p_np1 when n is at certain points, 5, 30 and 70 for example. How would I go about writing code for that?

Best Answer

idx = [5 30 70] ;
iwant = zeros([],[],length(idx)) ;
count = 0 ;
for n = 1:100
%first for loop for i = 2:end-1, second for loop for j = 2: end-1
for i = (2:Nx-1)
for j = (2:Ny-1)
%update equation
p_np1(i,j) = a^2 * (p_n(i+1,j) + p_n(i-1,j) ...
- 4*p_n(i,j) + p_n(i, j+1) + p_n(i, j-1)) ...
+ 2*p_n(i,j) - p_nm1(i,j);
end
end
if any(idx==n)
count = count+1 ;
iwant(:,:,count) = p_np1 ;
end
% after each iteration, previous value becomes present
% pressure value
p_nm1 = p_n;
% after each iteration, present value becomes next pressure
% value
p_n = p_np1;
% Plotting continuous plot
% plot the field
imagesc(x_axis, y_axis, p_np1);
% set the limits on the y-axis, 'YDir' and 'normal' commands set the
% y-axis on the plot to go from low to high from bottom to top
set(gca, 'YDir', 'normal');
% adds title with the iteration number
title(['n = ' num2str(n)]);
% keeps updating plot
drawnow;
% briefly pause before continuing the loop
pause(0.1)
end