[VB.NET] 行列計算

2013年7月22日

 ちょっと行列計算が入用になったので作成。
 Double の二次元配列の 左側添え字を行/右側添字を列と見立てて計算します。

 エラー処理なし、逆行列の計算では行列が正則であるかどうかのチェックとかもなし。
 使う予定がなかったので、スカラー積や和を求めるメソッドもありません(汗
 

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





カテゴリー: Program, VB.NET

Follow comments via the RSS Feed | Leave a comment | Trackback URL

1 Comment to "[VB.NET] 行列計算"

  1. [VB.NET] 回帰分析 | オールトの雲

    [...] [VB.NET] 行列計算 [...]

コメントを投稿する

日本語が含まれない投稿は無視されますのでご注意ください。(スパム対策)


«   »
 
Powered by Wordpress and MySQL. Theme by Shlomi Noach, openark.org