-
Notifications
You must be signed in to change notification settings - Fork 1
/
tridiagonal_matrix.m
51 lines (46 loc) · 1.25 KB
/
tridiagonal_matrix.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
%==========================================================================
%
% tridiagonal_matrix Solves the tridiagonal linear system Ax = d for x
% using the matrix implementation of the tridiagonal matrix algorithm.
%
% x = tridiagonal_matrix(A,d)
%
% Copyright © 2021 Tamas Kis
% Last Update: 2022-10-22
% Website: https://tamaskis.github.io
% Contact: [email protected]
%
% TECHNICAL DOCUMENTATION:
% https://tamaskis.github.io/files/Tridiagonal_Matrix_Algorithm.pdf
%
%--------------------------------------------------------------------------
%
% ------
% INPUT:
% ------
% A - (n×n double) tridiagonal matrix
% d - (n×1 double) vector
%
% -------
% OUTPUT:
% -------
% x - (n×1 double) solution of the tridiagonal linear system Ax = d
%
%==========================================================================
function x = tridiagonal_matrix(A,d)
% determines n
n = length(d);
% preallocates x
x = zeros(n,1);
% forward elimination
for i = 2:n
w = A(i,i-1)/A(i-1,i-1);
A(i,i) = A(i,i)-w*A(i-1,i);
d(i) = d(i)-w*d(i-1);
end
% backward substitution
x(n) = d(n)/A(n,n);
for i = (n-1):(-1):1
x(i) = (d(i)-A(i,i+1)*x(i+1))/A(i,i);
end
end