%Problem 27.3, solving the heat diffusion problem using
%central finite differences
%To solve, we must put the problem into the form [CoeffMatrix]{x}={rhs}
clear
dx = .1
L=10
x = 0:dx:L
C = 2 + 0.15*dx^2
h = 1

%Generate coeffecient Matrix
for i=1:length(x)-2
    for j=1:length(x)-2
        if i==j
        CoeffMatrix(i,j)= C;
        end
        if j==(i+1)
            CoeffMatrix(i,j)= -1;
        end
        if j==(i-1)
            CoeffMatrix(i,j)= -1;
        end
    end
end

rhs = zeros(length(x)-2,1);
%Set the boundary conditions
rhs(1) = 240;
rhs(length(x)-2)=150;

%Solve for the temperatures
T_temp = inv(CoeffMatrix)*rhs;

T(1)=240;
T(length(x))=150;
for i=2:length(x)-1
    T(i)=T_temp(i-1);
end

%Calculate the exact solution
T_exact = 3.016944*exp(sqrt(0.15)*x) + 236.9831*exp(-sqrt(0.15)*x);
%plot Temperatures
plot(x,T,'o',x,T_exact)
legend('Finite Difference','Exact Solution')