如何在Matlab上以交替方式运行两个循环?

时间:2017-07-24 12:19:28

标签: matlab loops pde

我想用Matlab计算两个有限差分循环,如果我们有两个方程式,比如说(1)和(2),它完成一步(1)然后求解(2)然后是一步(1),然后是(2),然后是(2),依此类推。

为此,我提供了以下代码的参数:

%% Parameters

L = 5; % size of domain 
T = 5; % measurement time
dx = 1e-2; % spatial step
dt = 1e-3; % time step
x0 = 0;
c = 1;

%%

t = 0:dt:T; % time vector
x = (0:dx:L)'; % spatial vector
nt = length(t);
nx = length(x);
Lx = (1/dx^2)*spdiags(ones(nx,1)*[1 -2 1],-1:1,nx,nx); % discrete Laplace operator
mu = dt/dx;
I = eye(nx,nx); % identity matrix
A = spdiags(ones(nx,1)*[-1 1 0],-1:1,nx,nx); % finite difference matrix

然后第一个循环由

给出
%% Finite Difference Equation (1)

% preallocate memory
u = zeros(nx,nt);
v = zeros(nx,nt);
% initial condition in time
u(:,1) = sinc((x-x0)/dx);
v(:,1) = sinc((x-x0)/dx);
for i = 1:nx-1
    u(:,i+1) = ((1/(c*dt))*I+(1/dx)*A)\((1/(c*dt))*u(:,i)+v(:,i));
end

,第二个等式(2)由

给出
%% Finite Difference Equation (2)

% preallocate memory
u = zeros(nx,nt);
v = zeros(nx,nt);
% final condition in time
u(:,nt) = sinc((x-x0)/dt);
% initial condition in space
for j = nt:-1:2
    v(:,j-1) = ((1/dx)*A+(1/(c*dt))*I)\((1/(c*dt))*v(:,j)
end

在当前格式中,Matlab将运行第一个循环i = 1:nx-1,然后运行第二个循环j = nt:-1:2

但我想按如下方式运行两个循环:i = 1,然后是j = nt,然后是i = 2,然后是j = nt-1,依此类推。我该如何编码?

2 个答案:

答案 0 :(得分:1)

您可以合成两个循环,如下所示:

% define other variables and preallocations
j = nt;
for i = 1:nx-1 
    u(:,i+1) = ((1/(c*dt))*I+(1/dx)*A)\((1/(c*dt))*u(:,i)+v(:,i));
    v(:,j-1) = ((1/dx)*A+(1/(c*dt))*I)\((1/(c*dt))*v(:,j)
    j = j - 1;
end

答案 1 :(得分:1)

for i = 1:nx-1
    u(:,i+1) = ((1/(c*dt))*I+(1/dx)*A)\((1/(c*dt))*u(:,i)+v(:,i));
    %This if will be true once each 10 iterations
    if(mod((nt-i),10)==0)
        j=((nt-i)/10)+1;
        v(:,j-1) = ((1/dx)*A+(1/(c*dt))*I)\((1/(c*dt))*v(:,j);
    end
end

不知道这是否有效,但是当你尝试我的想法时,它会更有用。