% Solve the Heat Equation Using Backward Euler
clear all
L=1;
T=0.2;
Nx=50;
Nt=10;
a=1;
f=@(x) 0*x;
g1=@(t) 0;
g2=@(t) 0;
hx=L/Nx;
ht=T/Nt;
m=Nx-1;
xn=hx*[1:m]';
fn=f(xn);
fn1=fn(1);
fnm=fn(m);
for i=m:-1:1
    A(i,i)=-2;
end
for i=1:m-1
    A(i,i+1)=1;
    A(i+1,i)=1;
end
B=eye(m)-ht*a/hx^2*A;

un=sin(pi*xn);
for i=1:Nt
    tn=i*ht;
    fn(1)=fn1+a/hx^2*g1(tn);
    fn(m)=fnm+a/hx^2*g2(tn);
    un=B\(un+ht*fn);
    U(:,i)=un;
end
surf([1:Nt]*ht,xn,U);
