Here is an updated version of the code. I also used matlab pdepe function to validate the results which seem to agree with one another. However, the result obtained from matlab pdepe is more superior than the finite difference method.
clear variables
close all
n = 20;
Lx = 1;
dx = Lx/(n-1);
x = 0:dx:Lx;
m = 100;
tf = 1;
dt = tf/(m-1);
t = 0:dt:tf;
Fo = .5;
f = @(x)sin(pi/2*x)+(1/2)*sin(2*pi*x);
g1 = @(t)0;
g2 = @(t)exp(-pi^2/4*t);
u = zeros(n,m);
u(2:n,1) = f(x(2:n));
u(1,:) = g1(t);
u(n,:) = g2(t);
for k = 2:m-1
for i= 2:n-1
u(i,k+1) = Fo*(u(i-1,k)+u(i+1,k))+(1-2*Fo)*u(i,k);
end
end
figure
hold all
for i=1:4:numel(t)
plot(x,u(:,i),'linewidth',1.5,'DisplayName',sprintf('t = %1.2f',t(i)))
end
a = ylabel('Heat');
set(a,'Fontsize',14);
a = xlabel('x');
set(a,'Fontsize',14);
a=title(['Using The Explicit Method - Fo =' num2str(Fo)]);
set(a,'Fontsize',16);
legend('-DynamicLegend','location','bestoutside');
grid;
figure
[X, T] = meshgrid(x,t);
s2 = mesh(X',T',u);
title(['3-D plot of the 1D Heat Equation using the Explicit Method - Fo =' num2str(Fo)])
set(s2,'FaceColor',[0 0 1],'edgecolor',[0 0 0],'LineStyle','--');
a = title('Exact solution of the 1D Diffusivity Equation');
set(a,'fontsize',14);
a = xlabel('x');
set(a,'fontsize',20);
a = ylabel('y');
set(a,'fontsize',20);
a = zlabel('z');
set(a,'fontsize',20);
Here is the result from the pdepe function.
function PDEPE_diff
m = 0;
n = 20;
Lx = 1;
dx = Lx/(n-1);
x = 0:dx:Lx;
N = 100;
tf = 1;
dt = tf/(N-1);
t = 0:dt:tf;
sol = pdepe(m,@pdepfun,@icfun,@bcfun,x,t);
u = sol(:,:,1);
figure
hold all
for i=1:4:numel(t)
plot(x,sol(i,:),'linewidth',1.5,'DisplayName',sprintf('t = %1.2f',t(i)))
end
title('Numerical solution computed using PDEPE function.')
xlabel('Distance x')
ylabel('Time t')
legend('-DynamicLegend','location','bestoutside');
grid
figure
s2 = surf(x,t,u);
set(s2,'FaceColor',[0 0 1],'edgecolor',[0 0 0],'LineStyle','--');
title('u1(x,t)')
xlabel('Distance x')
ylabel('Time t')
function [g,f,s] = pdepfun(x,t,u,DuDx)
g = 1;
f = DuDx;
s = 0;
function u0 = icfun(x)
u0 = sin(pi/2*x)+(1/2)*sin(2*pi*x);
function [pl,ql,pr,qr] = bcfun(xl,ul,xr,ur,t)
pl = ul;
ql = 0;
pr = ur-exp(-pi^2/4*t);
qr = 0;
Best Answer