# How to fix this error Index exceeds the number of array elements (1) for a linear advection problem ?

32 views (last 30 days)
Zahraa on 28 Sep 2020 at 16:32
Answered: Walter Roberson on 29 Sep 2020 at 18:20
the problem statement is a linear advection equation with these following conditions and use grid spacing of dx=1 and apply time setp dt based on CFL numbers 0.5,0.8,1.0. Compute the solution for 100 time steps. To solve this problem I have to use explicit upwind differencing (FTBS).
here is my attempted code, I'm not sure how to fix this code
%define variable
xmin = 0; %min value of x
xmax = 250; %max value of x
dx=1;
c=250; %velcoity
CFL=0.5;
dt=(CFL*dx)/c;
tmax = 100; % max value of t
t=0; %time
N=100; %number of nodes-1
% discretise the domain
x=xmin:dx:xmax;
%set initial condition
for i=1:xmax
if (0<=x(i))&&(x(i)<=50)
u0=0;
elseif (50<=x(i))&&(x(i)<=110)
u0=100*sin(pi*(x-50)/60);
else (110<=x(i))&&(x(i)<=250);
u0=0;
end
end
% loop through time
nsteps = tmax/dt;
for n=1:nsteps
u=u0;
unp1=u0;
%Boundary conditions
u(:)=0;
%upwind scheme
for i = 2:N+2
unp1(i)=u(i)-CFL*(u(i)-u(i-1));
end
%update t and u
t = t+dt;
u = unp1;
%Plot solution
plot(x,u,'bo-','markerfacecolor','b');
pause(0.01);
end

#### 1 Comment

KSSV on 29 Sep 2020 at 17:08
Your u is a scalr and you are trying to access it like a vector.

Walter Roberson on 29 Sep 2020 at 18:20
for i=1:xmax
if (0<=x(i))&&(x(i)<=50)
u0(i)=0;
elseif (50<=x(i))&&(x(i)<=110)
u0(i)=100*sin(pi*(x-50)/60);
else (110<=x(i))&&(x(i)<=250);
u0(i)=0;
else
u0(i)=nan;
end
end