显式前向欧拉法
源程序:
function [u,x,t] = EF_Euler(A,xf,T,it0,bx0,bxf,M,N)
%解方程 A u_xx = u_t , 0 <= x <= xf, 0 <= t <= T
%初值: u(x,0) = it0(x)
% 边界条件: u(0,t) = bx0(t), u(xf,t) = bxf(t)
% M : x 轴的等分段数
% N : t 轴的等分段数
dx = xf/M; x = [0:M]*dx;
dt = T/N; t = [0:N]'*dt;
for i= 1:M + 1
u(i,1) =it0(x(i));
end
for j = 1:N + 1
u([1 M + 1],j)= [bx0(t(j)); bxf(t(j))];
end
r = A*dt/dx/dx, r1 = 1 - 2*r;
if(r>0.5)
disp('r>0.5,unstability');
end
for j = 1:N
for i = 2:M
u(i,j+1) =r*(u(i + 1,j) + u(i-1,j)) + r1*u(i,j); %(9.2.3)
end
end
u=u';
%------------------------------------
在MATLAB中编写脚本文件:
A = 0.5; %方程系数
it0 = inline('sin(pi*x)','x'); %初始条件
bx0 = inline('0'); bxf = inline('0'); %边界条件
xf = 2; M = 80; T = 0.1; N = 100;
[u1,x,t] = EF_Euler(A,xf,T,it0,bx0,bxf,M,N);
figure(1),clf,mesh(u1)
xlabel('x')
ylabel('t')
zlabel('U')
title('r>0.5')
M=50;
[u1,x,t] = EF_Euler(A,xf,T,it0,bx0,bxf,M,N);
figure(2),clf,mesh(u1)
xlabel('x')
ylabel('t')
zlabel('U')
title('r<0.5')
%-----------------
隐式后向欧拉法
源程序:
function [u,x,t] = IB_Euler(A,xf,T,it0,bx0,bxf,M,N)
%解方程 A1 u_xx = u_t , 0 <= x <= xf, 0 <= t <= T
%初值: u(x,0) = it0(x)
% 边界条件: u(0,t) = bx0(t), u(xf,t) = bxf(t)
% M : x 轴的等分段数
% N : t 轴的等分段数
dx = xf/M; x = [0:M]*dx;
dt = T/N; t = [0:N]'*dt;
for i = 1:M + 1
u(i,1) =it0(x(i));
end
for j = 1:N + 1
u([1 M + 1],j)= [bx0(t(j)); bxf(t(j))];
end
r = A*dt/dx/dx;
r2 = 1 + 2*r;
for i = 1:M - 1
P(i,i) = r2; %构造9.2.9的矩阵
if i > 1
P(i - 1,i)= -r; P(i,i - 1) = -r;
end
end
for j = 2:N + 1
b = [r*u(1,j);zeros(M - 3,1); r*u(M + 1,j)] + u(2:M,j - 1); %Eq.(9.2.9)
u(2:M,j) =linsolve(P,b);
end
u=u';
%---------------------
在MATLAB中编写脚本文件:
A= 0.5; %方程系数
it0 = inline('sin(pi*x)','x'); %初始条件
bx0 = inline('0'); bxf = inline('0'); %边界条件
xf = 2; M = 50; T = 0.1; N = 100;
[u1,x,t] = IB_Euler(A,xf,T,it0,bx0,bxf,M,N);
mesh(u1)
xlabel('x')
ylabel('t')
zlabel('U')
%--------------
Grank-Nicholson方法
源程序:
function [u,x,t] =Grank_Nicholson(A,xf,T,it0,bx0,bxf,M,N)
%解方程 A u_xx = u_t , 0 <= x <= xf, 0 <= t <= T
%初值: u(x,0) = it0(x)
% 边界条件: u(0,t) = bx0(t), u(xf,t) = bxf(t)
% M : x 轴的等分段数
% N : t 轴的等分段数
dx = xf/M; x = [0:M]*dx;
dt = T/N; t = [0:N]'*dt;
for i = 1:M + 1
u(i,1) =it0(x(i));
end
for n = 1:N + 1
u([1 M + 1],n)= [bx0(t(n)); bxf(t(n))];
end
r = A*dt/dx/dx;
r1 = 2*(1 + r); r2 = 2*(1 - r);
for i = 1:M - 1
P(i,i) = r1; %(9.2.17)
Q(i,i)=r2;
if i > 1
P(i - 1,i)= -r; P(i,i - 1) = -r; %(9.2.17)等式左边矩阵
Q(i - 1,i)= r; Q(i,i - 1) = r;%(9.2.17)等式右边矩阵
end
end
for k = 2:N + 1
b=Q*u(2:M,k-1)+[r*(u(1,k)+u(1,k-1));zeros(M-2,1)];
u(2:M,k) =linsolve(P,b); %(9.2.17)
end
u=u';
%-----------
在MATLAB中编写脚本文件:
A= 0.5; %方程系数
it0 = inline('sin(pi*x)','x'); %初始条件
bx0 = inline('0'); bxf = inline('0'); %边界条件
xf = 2; M = 25; T = 0.1; N = 100;
[u1,x,t] = Grank_Nicholson(A,xf,T,it0,bx0,bxf,M,N);
mesh(u1)
xlabel('x')
ylabel('t')
zlabel('U')