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

1 view (last 30 days)
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

Answers (1)

Walter Roberson
Walter Roberson on 29 Sep 2020
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

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!