% Thomas Algorithm for tridiagonal system of equations of the form [a][x] = [b]

% ab is the combined matrix of matrix a and vector b
% n - No. of rows in matrix ab
% m - No. of columns in matrix ab

clear
clc

% Read from an external file
%{
 filename = 'thomas_algorithm_data1.xlsx';
 sheet = 1;
 xlRange = 'A1:CW100';
ab = xlsread(filename,sheet,xlRange)
[n,m] = size(ab);
%}

% Matrix ab
ab = [ -2.25 1 0 0 0 0 0 0; 1 -2.25 1 0 0 0 0 0; 0 1 -2.25 1 0 0 0 0; 0 0 1 -2.25 1 0 0 0; 0 0 0 1 -2.25 1 0 0; 0 0 0 0 1 -2.25 1 0; 0 0 0 0 0 1 -2.25 100 ]
[n,m] = size(ab)

% Obtain "a" matrix from ab
for i = 1:n
    for j = 1:m-1
a(i,j) = ab(i,j);
    end
end
A = a

% Obtain "b" column vector from ab
for i = 1:n
    for j = m-1:m
b(i) = ab(i,j);
    end
end
B = b'

% Algorithm

for i = 1:n
    for j = 1:m-1
        if i == j
            d(i) = a(i,j);
        elseif i == j+1
            l(i) = a(i,j);
        elseif i == j-1
            u(i) = a(i,j);
        end
    end
end
u(n) = 0;
d = d';
l = l';
u = u';
new = [ l d u ]

for i = 2:n
    d(i) = d(i) - (l(i)/d(i-1))*u(i-1);
    b(i) = b(i) - (l(i)/d(i-1))*b(i-1);
end

x(n) = b(n)/d(n);

for k = 1:n-1
    i = n-k;
    x(i) = (b(i) - u(i)*x(i+1))/d(i);
end

% x vector is the solution 
disp("solution")
for i = 1:n
    fprintf('x(%d) = %8.4f\n', i, x(i));
end

% verification
x1 = A\B   % Matlab built-in function

