Jason Born
Jason Born

Reputation: 173

How to run two loops in alternating fashion on Matlab?

I would like to use Matlab to compute two finite difference loops in such a manner that if we have two equations, let's say (1) and (2), it completes one step of (1) then solves (2) for one step then (1) for the next step and then (2) and so on and so forth.

To this end, I provide the parameters of my code below:

%% 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

Then the first loop is given by

%% 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

and the second equation (2) is given by

%% 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

In the current format, Matlab will run the first loop i = 1:nx-1 and then the second loop j = nt:-1:2.

But I want to run the two loops as follows: i = 1, then j = nt, then i = 2, then j = nt-1 and so on and so forth. How should I code this?

Upvotes: 0

Views: 116

Answers (2)

Ivan
Ivan

Reputation: 782

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

Don't really know if this will work, but making it more usable as you are trying my idea.

Upvotes: 1

OmG
OmG

Reputation: 18838

You can composite two loops like the following:

% 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

Upvotes: 1

Related Questions