How to Use a Matrix in Vb.Net
A matrix is a grid and each location in this grid contains a piece of information. Take a chessboard for example: It is a matrix and each square is one of its elements. Matrices are useful in real life to represent large amounts of data. The data can be processed more conveniently because it is represented in a concise manner. Using a matrix in VB.NET is just like using it in math. However, you must know how to write code to work with matrices.
Instructions
-
-
1
Open VB.NET and create a TWO-dimensional array. You must first declare a class for your new matrix. You use the "M" variable for the number of columns and the "N" variable for the number of rows. Here is the code to generate this class in VB.NET:
Public Class Matrix
Implements ICloneable
Private M As Integer
Private N As Integer
Public val(,) As Double
Private currentX As Integer
Private currentY As Integer
End ClassNote that the number of columns and the number of rows are integers. "val(,)" is an array with two dimensions that contains the elements of your matrix.
-
2
Assign proper dimensions to your matrix in the class constructor by using this code:
Public Sub New(ByVal X As Integer, ByVal Y As Integer)
SetDimensions(X, Y)
currentX = 0
currentY = 0
End SubHere is how you create a square matrix:
Public Sub New(ByVal X As Integer)
SetDimensions(X, X)
currentX = 0
currentY = 0
End Sub -
-
3
Add one matrix to another by using a function that takes a matrix as a parameter and does element-by-element addition. The result will be a matrix. Use this code for your function:
Public Function Add(ByVal C As Matrix) As Matrix
If M <> C.M Or N <> C.N Then
Throw New Exception("Matrices size Mismatch.")
End If
Dim B As Matrix = New Matrix(M, N)
For i As Integer = 0 To M - 1
For j As Integer = 0 To N - 1
B.val(i, j) = val(i, j) + C.val(i, j)
Next
Next
Return B
End Function -
4
Multiply one matrix by another by using a function that returns a matrix. Note that you can only multiply two matrices only if the number of columns of the first is equal to the number of rows of the second. This function multiplies matrix "X" with matrix "Y," and returns the new matrix:
public class Test
public Shared Sub Main
Dim X As New Matrix(2.0F, 1.0F, 3.0F, 1.0F, 0.0F, 4.0F)
Dim Y As New Matrix(0.0F, 1.0F, -1.0F, 0.0F, 0.0F, 0.0F)
X.Multiply(Y, MatrixOrder.Append)
Dim i As Integer
For i = 0 To X.Elements.Length - 1
Console.WriteLine(X.Elements(i).ToString())
Next i
End Sub
End classNote that this function also reads the resulting matrix.
-
5
Raise a matrix to power by multiplying it with itself.
-
1
References
Resources
- Photo Credit Ablestock.com/AbleStock.com/Getty Images