Evaluate the determinant of a square matrix by using Gauss Elimination with maximization of pivot elements. (線上執行) (原始碼下載)
行列式的符號表示法類似矩陣的型式,差別在於矩陣是以兩個中括號將元素包圍起來,而行列式是以兩條直線將元素包圍起來。行列式值(determinant)在解線性聯立方程式系統時占有舉足輕重的地位,若且為若一個線性聯立方程式系統的係數矩陣之行列式值不等於 0,則此系統具有唯一解。行列式可以是 m×n 矩陣,但是一般我們常碰到的問題都是解決 n×n 矩陣的行列式問題,也就是方陣(square matrix)的行列式問題,因此我們可以利用行列式的性質,以高斯消去法將方陣化簡成上三角矩陣之後,則該方陣的行列式值即為對角線元素相乘之值。以下的副程式使用了高斯消去法配合 pivoting strategy,如此可將捨入誤差(roundoff error)降至最小,並避免除以零的問題。關於行列式更進一步的介紹,請參閱市面上的數值分析書籍。
副程式:
Public Function Determinant(m() As Single) As Single Dim i As Long, j As Long, k As Long, row As Long, order As Long Dim r As Long, c As Long, Pivot As Single, Pivot2 As Single, temp() As Single Determinant = 1 row = UBound(m, 1) If UBound(m, 2) <> row Then MsgBox "這不是方陣": Exit Function ReDim temp(1 To row) For i = 1 To row Pivot = 0 For j = i To row For k = i To row If Abs(m(k, j)) > Pivot Then Pivot = Abs(m(k, j)) r = k: c = j End If Next k Next j If Pivot = 0 Then Determinant = 0: Exit Function If r <> i Then order = order + 1 For j = 1 To row temp(j) = m(i, j) m(i, j) = m(r, j) m(r, j) = temp(j) Next j End If If c <> i Then order = order + 1 For j = 1 To row temp(j) = m(j, i) m(j, i) = m(j, c) m(j, c) = temp(j) Next j End If Pivot = m(i, i) Determinant = Determinant * Pivot For j = i + 1 To row Pivot2 = m(j, i) If Pivot2 <> 0 Then For k = 1 To row m(j, k) = m(j, k) - m(i, k) * Pivot2 / Pivot Next End If Next Next Determinant = Determinant * (-1) ^ order End Function
參數說明:
m():欲求行列式之方陣。
範例:
1.由鍵盤輸入矩陣元素:
Private Sub Command1_Click() Dim Keyin As String, m() As Single Keyin = InputBox("請輸入方陣(square matrix)," _ & "以分號"";""來分隔列元素,以空白來分隔行元素。" _ & vbNewLine & "例如有一3×3的矩陣:" & vbNewLine & "1 2 3" & vbNewLine & _ "4 5 6 " & vbNewLine & "7 8 9" & vbNewLine & "則輸入: 1 2 3;4 5 6;7 8 9 ") If SepStrToMatrix(Keyin, ";", " ", m) Then Debug.Print Determinant(m) Else MsgBox "矩陣輸入有誤,請重新輸入。" End If End Sub其中 SepStrToMatrix 這個副程式,請參閱本站的 將字串拆解成陣列。
若有一方陣如下:
2 -1 3 0 4 -2 7 0 -3 -4 1 5 6 -6 8 0執行 Command1,並在 Inputbox 中輸入 2 -1 3 0;4 -2 7 0;-3 -4 1 5; 6 -6 8 0,在 VB 的即時運算視窗可得此方陣的 Determinant= -30。
2.由檔案讀入矩陣元素:
Private Sub Command2_Click() Dim FileNo As Long, Keyin As String Dim temp As String, m() As Single FileNo = FreeFile Open "c:\users\det.txt" For Input As #FileNo Do While Not EOF(FileNo) Line Input #FileNo, temp If Trim(temp) <> "" Then Keyin = Keyin & temp & ";" Loop Close #FileNo Keyin = Mid(Keyin, 1, Len(Keyin) - 1) If SepStrToMatrix(Keyin, ";", " ", m) Then Debug.Print Determinant(m) Else MsgBox "方陣輸入有誤,請重新輸入。" End If End Sub其中 SepStrToMatrix 這個副程式,請參閱本站的 將字串拆解成陣列。
若有一矩陣儲存在 "C:\users\det.txt" 如下所示:
1 1 0 3 2 1 -1 1 -1 2 3 -1 3 -1 -1 2執行 Command2 之後,在 VB 的即時運算視窗可得此方陣的 Determinant= -39。
[ 上一個 |
首頁 | 數值分析 | 下一個 ] This page was written by Jaric on May. 8, 1999. All rights reserved.Total pageview since 4/6/1999.