Heat equation forward finite difference method MATLAB

464 Views Asked by At

my code for forward difference equation in heat equation does not work, could someone help? The problem is in Line 5, saying that t is undefined, but f is a function with x and t two variables. How should I define t? Thanks!

function w=heatfd(xl,xr,yb,yt,M,N)
% input: space interval [xl,xr], time interval [yb,yt],
%        number of space steps M, number of time steps N
% output: solution w
f(x,t) = exp(t-x);
f=@(x) exp (-x); 
c_1 = exp(t);
c_2 = exp(t-1);
l=@(t) c_1*t;
r=@(t) c_2*t;
D=1;                               % diffusion coefficient
T = yt - yb;
h=(xr-xl)/M; k=T/N; m=M-1; n=N;
sigma=D*k/(h*h);
a=diag(1-2*sigma*ones(m,1))+diag(sigma*ones(m-1,1),1);
a=a+diag(sigma*ones(m-1,1),-1);    % define matrix a
lside=l(yb+(0:n)*k); rside=r(yb+(0:n)*k);
w(:,1)=f(xl+(1:m)*h)';             % initial conditions
for j=1:n
  w(:,j+1)=a*w(:,j)+sigma*[lside(j);zeros(m-2,1);rside(j)];
end
w=[lside;w;rside];                 % attach boundary conds
x=(0:m+1)*h;t=(0:n)*k;
mesh(x,t,w')                       % 3-D plot of solution w
view(60,30);axis([xl xr yb yt -2 2])
1

There are 1 best solutions below

3
On

I didn't look at the later parts of your code, but the obvious issues are corrected up to this point.

function w=heatfd(xl,xr,yb,yt,M,N)
% input: space interval [xl,xr], time interval [yb,yt],
%        number of space steps M, number of time steps N
% output: solution w
u=@(x,t)= exp(t-x); %not sure you actually use this for anything...
f=@(x) exp (-x); 
l=@(t) exp(t).*t;
r=@(t) exp(t-1).*t;

Note that the c_1 and c_2 variables were completely superfluous. Also note that you needed .* because you plugged vectors directly into l and r (rather than using a loop). You also seem to be using some conventions that arise from the symbolic toolbox, such as declaring functions with f(...)=... notation. Stop doing that; only use symbolic toolbox conventions if you're using symbolic toolbox utilities (such as symbolic differentiation).