%参考课本
%slove program by explicit scheme
%u(j,n+1)=u(j,n)+v*(u(j+1,n)-2*u(j,n)+u(j-1,n))
xl=0;
xr=1;
j=10;
dx=(xr-xl)/j;%步长
tf=0.1;
Nt=50;
dt=tf/Nt;
mu=dt/(dx)^2;
%make sure dt satisy stability condition
if mu>0.5
error('mu shuold<0.5!')
end
%initial condition
x=xl:dx:xr;%grind point
f=sin(pi*x)+sin(2*pi*x);
%store the solution at all grid points forall time steps
u=zeros(j+1,Nt);
u_ture=zeros(j+1,Nt);
%find the approximate solution at each time step
for n=1:Nt
t=n*dt;
%boundary condition at left side
gl=exp(-1*pi*pi*t).*sin(pi*xl)+exp(-4*pi*pi*t).*sin(2*pi*xl);
%boundary condition at right side
gr=exp(-1*pi*pi*t).*sin(pi*xr)+exp(-4*pi*pi*t).*sin(2*pi*xr);
if n==1for i=2:j
u(i,n)=f(i)+mu*(f(j+1)-2*f(j)+f(j-1));
end
u(1,n)=gl;
u(j+1)=gr;
elsefor i=2:j
u(i,n)=u(i,n-1)+mu*(u(i+1,n-1)-2*u(i,n-1)+u(i-1,n-1));
end
u(1,n)=gl;
u(j+1)=gr;
end
%calculate the analytic solution
for i=1:j+1
xi=xl+(i-1)*dx;
u_ture(i,n)=exp(-1*pi*pi*t).*sin(pi*xi)+exp(-4*pi*pi*t).*sin(2*pi*xi);
end
end
%plot the result
tt=dt:dt:Nt*dt;
figure(1)
colormap(gray);
surf(x,tt,u');
xlabel('x');
ylabel('t');
zlabel('u');
title('explicit scheme')
%polt the analytic result
figure(2)
colormap(jet);
surf(x,tt,u_ture');
xlabel('x');
ylabel('t');
zlabel('u');
title('analytic solution')