Skip to content

Instantly share code, notes, and snippets.

@ooltcloud
Created December 30, 2014 15:02
Show Gist options
  • Save ooltcloud/ef78cf66465d37952098 to your computer and use it in GitHub Desktop.
Save ooltcloud/ef78cf66465d37952098 to your computer and use it in GitHub Desktop.
簡易行列計算
Public Class Matrix
''' <summary>
''' 乗算
''' </summary>
Public Shared Function Multiply(multiplicandMatrix As Double(,),
multiplierMatrix As Double(,)) As Double(,)
Dim matA = multiplicandMatrix
Dim matB = multiplierMatrix
' 行数/列数確定
Dim L = matA.GetUpperBound(0)
Dim M = matA.GetUpperBound(1)
If M <> matB.GetUpperBound(0) Then
Throw New Exception("被乗数の列の個数と、乗数の行の個数が違います")
End If
Dim N = matB.GetUpperBound(1)
' 結果用
Dim matR(L, N) As Double
' 乗算
For i = 0 To L
For j = 0 To N
For k = 0 To M
matR(i, j) += matA(i, k) * matB(k, j)
Next
Next
Next
Return matR
End Function
''' <summary>
''' 逆行列
''' </summary>
Public Shared Function Inverse(regularMatrix As Double(,)) As Double(,)
Dim matA = regularMatrix
Dim N = matA.GetUpperBound(0)
Dim matR = E(N + 1)
For i = 0 To N
Dim a = matA(i, i)
' 除算
For j = 0 To N
matA(i, j) /= a
matR(i, j) /= a
Next
' 掃出し
For j = 0 To N
If (j <> i) Then
Dim b = matA(j, i)
For k = 0 To N
matA(j, k) -= matA(i, k) * b
matR(j, k) -= matR(i, k) * b
Next
End If
Next
Next
Return matR
End Function
''' <summary>
''' 単位行列
''' </summary>
Public Shared Function E(degree As Integer) As Double(,)
Dim N = degree - 1
Dim matR(N, N) As Double
For i = 0 To N
matR(i, i) = 1
Next
Return matR
End Function
''' <summary>
''' 転置行列
''' </summary>
Public Shared Function Transpose(matA As Double(,)) As Double(,)
Dim M = matA.GetUpperBound(0)
Dim N = matA.GetUpperBound(1)
Dim matR(N, M) As Double
For i = 0 To M
For j = 0 To N
matR(j, i) = matA(i, j)
Next
Next
Return matR
End Function
End Class
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment