追赶法(Thomas Algorithm)的MATLAB实现

追赶法求解特殊方程组Ax=f

原理

考虑如下特殊的线性方程组,记为Ax=f,称为三对角方程组,其系数矩阵称为三对角矩阵。

A=LU,其中LU分别为

迭代公式:

MATLAB实现

thomas.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
function [l,u,x] = thomas(b,a,c,f)
%% 输入参数
% b: 矩阵A的对角线元素;
% a: 设a1 = 0, a2 ~ an
% c: c1 ~ cn-1
% f: Ax = f
%% 初始化参数
cnt = length(b);
l = zeros(cnt,1);
u = zeros(cnt,1);
y = zeros(cnt,1);
x = zeros(cnt,1);
%% 迭代过程
u(1) = b(1);
y(1) = f(1);
for i = 2 : cnt
l(i) = a(i) / u(i - 1);
u(i) = b(i) - l(i) * c(i - 1);
y(i) = f(i) - l(i) * y(i - 1);
end
x(cnt) = y(cnt) / u(cnt);
for i = cnt - 1 : -1 : 1
x(i) = (y(i) - c(i) * x(i + 1)) / u(i);
end

end

测试用例

1
2
3
4
5
6
7
8
9
%% 测试用例
% b = [0.5; 0.8; 1; 2];
% a = [0; 0.35; 0.25; 1];
% c = [0.25; 0.4; 0.5];
% f = [0.35; 0.77; -0.5; -2.25];
% b = [2 2 2 2];
% a = [0 -1 -1 -1];
% c = [-1 -1 -1];
% f = [1 0 0 1];
Author: MichaelWin
Link: http://blogs.tcaue.cn/thomas/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.