2

我编写了一个 VBA 代码来解决一组代数方程,其系数矩阵是三对角(称为 Thomas 算法)。方程具有形式

A(i)X(i-1)+B(i)X(i)+C(i)X(i+1)=R(i)

A、B、C 和 R 的值被传递给返回 X 值的函数。VBA 代码如下。

Option Base 1
Function TRIDI(ByVal Ac As Range, ByVal Bc As Range, ByVal Cc As Range, _
ByVal Rc As Range) As Variant
Dim BN As Single
Dim i As Integer
Dim II As Integer
Dim A() As Single, B() As Single, C() As Single, R() As Single, X() As Single
N = Ac.Rows.Count
ReDim A(N), B(N), C(N), R(N), X(N)
For i = 1 To N
A(i) = Ac.Parent.Cells(Ac.Row + i - 1, Ac.Column)
B(i) = Bc.Parent.Cells(Bc.Row + i - 1, Bc.Column)
C(i) = Cc.Parent.Cells(Cc.Row + i - 1, Cc.Column)
R(i) = Rc.Parent.Cells(Rc.Row + i - 1, Rc.Column)
Next i
A(N) = A(N) / B(N)
R(N) = R(N) / B(N)
For i = 2 To N
II = -i + N + 2
BN = 1 / (B(II - 1) - A(II) * C(II - 1))
A(II - 1) = A(II - 1) * BN
R(II - 1) = (R(II - 1) - C(II - 1) * R(II)) * BN
Next i
X(1) = R(1)
For i = 2 To N
X(i) = R(i) - A(i) * X(i - 1)
Next i
TRIDI = Application.WorksheetFunction.Transpose(X)
End Function

该函数适用于线性方程。如果方程是非线性的,例如对于下面的三个方程

X(1)=1

X(1)-2X(2)+X(3)=3+ X(1)^2

X(1)+X(3)=2

解是利用Excel的迭代功能迭代得到的,如下图。(我还不能发布图片,因为这是我的第一篇文章。如果你给我发电子邮件,bumedoc@gmail.com,我也可以把电子表格发给你)

     A    B    C     D                  E

1    A    B    C     R                  X

2    0    1    0     =1          =TRIDI(A2:A4,B2:B4,C2:C4,D2:D4)

3    1   -2    1     =3+E2^2     =TRIDI(A2:A4,B2:B4,C2:C4,D2:D4)

4    1    1    0     =2          =TRIDI(A2:A4,B2:B4,C2:C4,D2:D4)

但是,保存电子表格并再次打开后,我得到了#value!E2:E4 和 D3 中的错误。我假设在打开电子表格时,Excel 会尝试初始化具有循环引用的单元格并感到困惑。有没有人可以解决这个问题?

4

1 回答 1

1

替换为我=3+E2^2=IFERROR(3+E2^2,0)作品。

于 2013-04-14T21:23:17.357 回答