MATLAB: Index in position 1 exceeds array bounds (must not exceed 301) and Error in IMR_2psv (line 34) u(i,:)=(1/​16)*(-u(i-​2,:)+4*u(i​-1,:)+10*u​(i,:)+4*u(​i+1,:)-u(i​+2,:));

implicit midpoint rulenumerical method

clear;
Lmax = 1.0; % Maximum length
Tmax = 1.; % Maximum time
c = 1.0; % Advection velocity
maxt = 150; % Number of time steps
dt = Tmax/maxt;
n = 300; % Number of space steps
nint=15; % The wave-front: intermediate point from which u=0
dx = Lmax/n;
b = c*dt/(2.*dx);
for i = 1:(n+1)
if i < nint
u(i,1)=1.;
else
u(i,1)=0.;
end
x(i) =(i-1)*dx;
end
for k=1:maxt+1
u(1,k) = 1.;
u(n+1,k) = 0.;
time(k) = (k-1)*dt;
end
for k=1:maxt % Time loop
for i=3:n % Space loop
u(i,:)=(1/16)*(-u(i-2,:)+4*u(i-1,:)+10*u(i,:)+4*u(i+1,:)-u(i+2,:));
end
end

Best Answer

Your last loop go one step too far. u is 301x151 and n = 300. Then u(n+2) exceeds array bounds.
clear;
Lmax = 1.0; % Maximum length
Tmax = 1.; % Maximum time
c = 1.0; % Advection velocity
maxt = 150; % Number of time steps
dt = Tmax/maxt;
n = 300; % Number of space steps
nint=15; % The wave-front: intermediate point from which u=0
dx = Lmax/n;
b = c*dt/(2.*dx);
for i = 1:(n+1)
if i < nint
u(i,1)=1.;
else
u(i,1)=0.;
end
x(i) =(i-1)*dx;
end
for k=1:maxt+1
u(1,k) = 1.;
u(n+1,k) = 0.;
time(k) = (k-1)*dt;
end
for k=1:maxt % Time loop
for i=3:n-1 % Space loop
u(i,:)=(1/16)*(-u(i-2,:)+4*u(i-1,:)+10*u(i,:)+4*u(i+1,:)-u(i+2,:));
end
end