%MATLAB version of the FORTRAN program for Example 4.3 on page 155 
%of conte/deboor
%
%  Reference:
%
%    Samuel Conte, Carl de Boor,
%    Elementary Numerical Analysis,
%    Third Edition,
%    SIAM, 2017,
%    ISBN: 978-1-611975-19-2.
%
N = 10;
A = repmat([-1,2,-1 0], 10,1);
A(1,4) = 1;

A = TRID(A);
disp('  The solution is ')
fprintf(' %2d   %14.7e\n',[1:N;A(:,4)'])

function A = TRID(A)
% With  A =: [SUB,DIAG,SUP,B] the N by 4 matrix with columns SUB, DIAG, SUP, B, 
% the tridiagonal linear system
%   SUB(i)*?(i-1) + DIAG(i)*?(i) + SUP(i)*?(i+1) = B(i),  i=1:N,
% (with SUB(1) and SUP(N) taken to be zero) is solved by factorization
% and substitution. The factorization is returned in the columns
% SUB, DIAG, SUP of A, and  the solution is returned in column B .

[N,~] = size(A);
if N == 1, A(1,4) = A(1,4)/A(1,2); return, end
for i=2:N
   A(i,1) = A(i,1)/A(i-1,2);
   A(i,2) = A(i,2) - A(i,1)*A(i-1,3);
   A(i,4) = A(i,4) - A(i,1)*A(i-1,4); 
end
A(N,4) = A(N,4)/A(N,2);
for i=N-1:-1:1
   A(i,4) = (A(i,4) - A(i,3)*A(i+1,4))/A(i,2);
end
return, end
