% This program will solve a tri-diagonal system. If there is no solution or
% infinitely many solutions it will print an error message.
% The lower diagonal, diagonal and upper diagonal are loaded in.
% The RHS vector b is also loaded in.

fprintf(' This script solves tridiagonal systems of equations. \n');
fprintf(' You are to enter the names of the files containing \n');
fprintf(' the lower, diagonal, upper diagonals and the right hand side. \n');
fprintf(' \n');
filel = input(' The lower diagonal file name. ','s');
filed = input(' The diagonal file name. ','s');
fileu = input(' The upper diagonal file name. ','s');
fileb = input(' The right hand side file name. ','s');

load filel
load filed
load fileu
load fileb

l = filel;
d = filed;
u = fileu;
b = fileb;

n = length(b);  % get the size of the tri-diagonal

rowswitch(1:n) = 0;  % this will count and store the row switches 
r(1:n) = 0; % this is to handle the actual row switch
x(n+1) = 0; % this is set to zero so we can keep everything in one loop.
u(n) = 0; % set to zeroe so we can keep everything in one loop.

for i = 1:n-1
    if (abs(d(i))<=abs(l(i))) % if d(i) is smaller than l(i) a row switch
                              % reduces error
        if (l(i)==0)
            det = 0;
            break;
        end
        % The following switches row i with row i+1
        rowswitch(i) = 1;
        old = d(i); d(i) = l(i); l(i) = old;
        old = d(i+1); d(i+1) = u(i); u(i) = old;
        r(i) = u(i+1); u(i+1) = 0;
        old = b(i); b(i) = b(i+1); b(i+1) = old;
    end
    mult = -l(i)/d(i);
    d(i+1) = d(i+1)+mult*u(i);
    u(i+1) = u(i+1)+mult*r(i);
    b(i+1) = b(i+1)+mult*b(i);
end
x(n) = b(n)/d(n);
for j = n-1:-1:1
    x(j)=(b(j)-u(j)*x(j+1)-r(j)*x(j+2))/d(j);
end

disp(transpose(x(1:n)))

        
        
       
