Array.CreateInstance, Array.GetValue, Array.SetValueの各メソッドは、多次元配列でも使うことが出来ます。 次の例では、Array.CreateInstanceメソッドで指定された型の行列を表す2次元配列を作成し、Array.SetValueメソッドで値を設定して単位行列を構成しています。
Arrayクラスのメソッドを使って多次元配列の作成と要素の値の設定を行う (CreateInstance, GetValue, SetValue))
Imports System
Class Sample
' 任意の長さ・型の単位行列を生成する
Shared Function CreateIdentityMatrix(ByVal length As Integer, ByVal typeOfMatrix As Type) As Array
' 指定された型でlength×length行列となる2次元配列を作成
Dim matrix As Array = Array.CreateInstance(typeOfMatrix, length, length)
' 行列の対角成分に1、それ以外を0に設定する
For i As Integer = 0 To length - 1
For j As Integer = 0 To length - 1
If i = j Then
matrix.SetValue(1, i, j)
Else
matrix.SetValue(0, i, j)
End If
Next
Next
Return matrix
End Function
' 行列を表示する
Shared Sub PrintMatrix(ByVal matrix As Array)
For i As Integer = 0 To matrix.GetLength(1) - 1
Console.Write("(")
For j As Integer = 0 To matrix.GetLength(0) - 1
Console.Write("{0,-5} ", matrix.GetValue(i, j))
Next
Console.WriteLine(")")
Next
End Sub
Shared Sub Main()
' Integer型で2行2列の単位行列を作成
Dim matrix1 As Integer(,) = DirectCast(CreateIdentityMatrix(2, GetType(Integer)), Integer(,))
PrintMatrix(matrix1)
Console.WriteLine()
' Single型で4行4列の単位行列を作成
Dim matrix2 As Single(,) = DirectCast(CreateIdentityMatrix(4, GetType(Single)), Single(,))
' 行列内の各要素をスケーリング
For i As Integer = 0 To 3
For j As Integer = 0 To 3
matrix2(i, j) *= 0.25F
Next
Next
PrintMatrix(matrix2)
Console.WriteLine()
End Sub
End Class
実行結果
(1 0 ) (0 1 ) (0.25 0 0 0 ) (0 0.25 0 0 ) (0 0 0.25 0 ) (0 0 0 0.25 )