How do I save matrices from specific points in a 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?

 采纳的回答

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

4 个评论

Thanks for the response. Could you explain the code you've added? I'd like to understand it rather than just copy it in
@mathman: The code is commented and this should explain the purpose already. Which part is not clear yet?
@Jan, the comments in the code are my own. The additions he's added are not commented.
idx = [5 30 70] ;
iwant = zeros([],[],length(idx)) ;
count = 0 ;
if any(idx==n)
count = count+1 ;
iwant(:,:,count) = p_np1 ;
end
idx are the n values for which you want to save output.
iwant is initialised using zeros. It will be a 3d matrix.
if condition is met, the matrix is saved into iwant.

请先登录,再进行评论。

更多回答(0 个)

类别

帮助中心File Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by