I trying to make a Matlab code to plot a discrete solution of the heat equation using the implicit method.
The information I am given about the heat equation is the following:
d^2u/d^2x=du/dt
Initial conditions (t=0):
u=0 if x>0
Otherwise u=1 (when t=0)
The discrete implicit difference method can be written as follows:
(I+delta t*A)[v(m+1)]=v(m)
, where I is an identity matrix, delta t is the times space, m is the time-step number, v(m+1) is the v-value at the next time step. A is the matrix: A has the value 2 at the diagonal, while -1 both right below and right over this diagonal. All the other numbers are zero.
A=(1/dx^2)*
[2 -1 0 . . . 0
-1 2 -1 . . . .
0 . . . . . .
. . . . . 0
. . . . -1 2 -1
1 . . . 0 -1 2]
Without inserting the values, the symbols are written instead:
A=(1/dx^2)*
[alpha(1) gamma(1) 0 . . . . . . . . 0
beta(2) alpha(2) gamma(2) ... .. . 0
0 . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . 0
. . . . beta(n-1) alpha(n-1) gamma(n-1)
0 . . . 0 beta(n) alpha(n)]
L = 20.; % Length of the wire
T =0.1; % Final time
maxm = 2000; % Number of time steps
dt = T/maxm;
n = 70; % Number of space steps
dx = L/(n);
r = dt/(dx^2); % Stability parameter, r less or equal to 1/2
alpha(1)=2+(1/(r));
d(1)=alpha(1);
v(1)=0; % Boundary condition.
v(n)=1; %Boundary condition.
c(1)=v(0);
for k=2:n
beta(k)=-1;
gamma(k)=-1;
alpha(k)=2+(1/r);
m(k)=beta(k)/d(k-1);
d(k)=alpha(k)-(m(k)*gamma(k-1));
c(k)=v(k)-(m(k)*c(k-1));
v(n)=c(n)/d(n);
for k=n-1:1
v(k)=(c(k)-gamma(k)*v(k+1))/d(k);
end
end
The error message I get is the following:
Attempted to access v(2); index out of bounds because numel(v)=1.
Error in Implicit (line 37) c(k)=v(k)-(m(k)*c(k-1));
Does anyone know what I should write instead so that the error message disappear? Does the Matlab code look okay, or is there something I should change? David