%  Heat diffusion in one dimensional wire within the explicit FTCS method
clear;

% Parameters to define the heat equation and the range in space and time
cond = 1/2;		%  Heat conductivity parameter
L = 1.;  		%  Length of the wire
T =1.;			%  Final time

%  Parameters needded to solve the equation within the explicit method
Nt = 2400;					%  Number of time steps
Dt = T/Nt;                  %  Time step
Nx = 50;					%  Number of space steps
Dx = L/Nx;                  %  Space step
b = 2.*cond*Dt/(Dx*Dx);		% beta parameter in the finite-difference implementation
% Remember that the FTCS method is stable for b=<1

disp(b);

%  The initial condition: the initial temperature of the wire, in this example a sin function
for i = 1:Nx+1
        x(i) =(i-1)*Dx;     % We also define vector x, due to the space discretization
        u(i,1) =sin(pi*x(i));        
end
          
%  Boundary conditions: the temperature of the wire at the boundaries at any time (in this example T=0)
for k=1:Nt+1
        u(1,k) = 0.;
        u(Nx+1,k) = 0.;
        t(k) = (k-1)*Dt; % We also define vector t, due to the time discretization
end

%  Implementation of the explicit FTCS method
for k=1:Nt          %  Time Loop
   for i=2:Nx;		%  Space Loop  
      u(i,k+1) =u(i,k) + 0.5*b*(u(i-1,k)+u(i+1,k)-2.*u(i,k));   % Implementation of the FTCS method
   end
end

% Graphical representation of the temperature at different selected times
figure(1)
plot(x,u(:,1),'-b',x,u(:,round(Nt/100)),'--g',x,u(:,round(Nt/10)),':b',x,u(:,Nt),'-.r')
title('Temperature of the wire within the explicit FTCS method')
xlabel('X')
ylabel('T')

figure(2)
mesh(t,x,u)

title('Temperature of the wire within the explicit FTCS method')
xlabel('t')
ylabel('x')
