- #1
omer21
- 25
- 0
I am trying to solve the following pde numerically using backward f.d. for time and central difference approximation for x, in MATLAB but i can't get correct results.
[itex]
\frac{\partial u}{\partial t}=\alpha\frac{\partial^{2}u}{\partial x^{2}},\qquad u(x,0)=f(x),\qquad u_{x}(0,t)=0,\qquad u_{x}(1,t)=2
[/itex]
for boundary conditions i used the following approximation
[itex]u_{x}(0,t)=\frac{u_{i+1}^{j}-u_{i-1}^{j}}{2h}[/itex]
what is wrong with the code i wrote
[itex]
\frac{\partial u}{\partial t}=\alpha\frac{\partial^{2}u}{\partial x^{2}},\qquad u(x,0)=f(x),\qquad u_{x}(0,t)=0,\qquad u_{x}(1,t)=2
[/itex]
for boundary conditions i used the following approximation
[itex]u_{x}(0,t)=\frac{u_{i+1}^{j}-u_{i-1}^{j}}{2h}[/itex]
what is wrong with the code i wrote
Code:
function [T,exact]=implicitheat2(t_i,t_f,a,b,dx,dt,alpha)
%U_t=U_xx , 0<x<1, U(x,0)=x.^2+1+cos(pi.*x), U_x(0,t)=0, U_x(1,t)=2
% dt: step size in t
% dx: step size in x
% a: left point of domain
% b: right point of domain
% alpha: equal to 1
% call func. as implicitheat2(0,0.1,0,1,0.1,0.00001,1)
n=(t_f-t_i)/dt;
m=(b-a)/dx;
lambda=alpha*dt/dx^2;
if isinteger(m)==0
m=round(m);
end
if isinteger(n)==0
n=round(n);
end
T=zeros(m+1,n+1);
x=a:dx:b;
t=t_i:dt:t_f;
u0 = x.^2+1+cos(pi.*x);
T(:,1)=u0; %initial value
A = sparse(m-1,m-1);
for i=1:m-1
A(i,i-1) = -lambda;
A(i,i ) = (1+2*lambda);
A(i,i+1) = -lambda;
end
A(1,2)=-2*lambda;
A(end,end-1)=-2*lambda;
b=zeros(m-1,1);
for j=2:n+1
b=T(2:m,j-1);
b(1,1)=T(2,j-1)-2*0*lambda*dx; %T(0,j-1)-2*lambda*U'*dx
b(m-1,1)=T(m,j-1)+2*lambda*2*dx; %T(m+1,j-1)+2*lambda*U'*dx
T(2:m,j)=A\b;
end
T=T(:,1);
%exact soln
[xx,tt]=meshgrid(x,t);
exact=2.*tt+xx.^2+1+exp(-pi^2.*tt).*cos(pi.*xx);
exact=exact(end,:);