function x = tridiagsolve ( L, U, U2, b ) % % function x = tri_solve ( L, U, U2, b ) % % TRI_SOLVE solves a tridiagonal linear system factored by TRI_FACTOR. % % Input, real L(N-1), the subdiagonal elements of the unit lower % triangular factor of A. % % Input, real U(N), U2(N-1), the diagonal and superdiagonal elements % of the upper triangular factor of A. % % Input, real b(N), the right hand side. % % Output, real x(N), the solution of the linear system. % n = 3;%length ( U ); % % Solve L * y = b. % y = zeros(n,1); y(1) = b(1); for i = 2 : n y(i) = b(i) - L(i-1) * y(i-1); end % % Solve U * x = y. % %x = zeros(n,1); for i = n : -1 : 2 x(i) = y(i) / U(i); y(i-1) = y(i-1) - U2(i-1) * x(i); end x(1) = y(1) / U(1); end function x =getdiag(a,n) j = 1; i = 1; while i <= n dia(i) = a(i,j); i++; j++; end; x = dia; end function x =getsub(a,n) j = 1; i = 2; while j <= n-1 sub(j) = a(i,j); i++; j++; end; x = sub; end function x =getsuper(a,n) j = 2; i = 1; while i <= n-1 super(i) = a(i,j); i++; j++; end; x = super; end a=[1, 2, 0; 4, 5, 6; 0, 8, 9]; b = [1,2,3]; n = length(b); dia = getdiag(a,n); %[1,5,9] sub = getsub(a,n); %[4,8] super = getsuper(a,n); % [2,6] x = tridiagsolve(sub,dia,super,b); write("x = ",x);