Subtract Matrices

This algorithm finds difference between corresponding elements of two matrices.



									Public Structure Matrix
	Public _Matrix As Integer(,)
	Public Rows As Integer
	Public Columns As Integer

	Public Sub New(matrix As Integer(,), rows As Integer, columns As Integer)
		Me._Matrix = matrix
		Me.Rows = rows
		Me.Columns = columns
	End Sub
End Structure

Public Shared Function SubtractMatrices(firstMatrix As Matrix, secondMatrix As Matrix) As Matrix
	If firstMatrix.Rows = secondMatrix.Rows AndAlso firstMatrix.Columns = secondMatrix.Columns Then
		Dim sum As Integer(,) = New Integer(firstMatrix.Rows - 1, firstMatrix.Columns - 1) {}

		For i As Integer = 0 To firstMatrix.Rows - 1
			For j As Integer = 0 To firstMatrix.Columns - 1
				sum(i, j) = firstMatrix._Matrix(i, j) - secondMatrix._Matrix(i, j)
			Next
		Next

		Return New Matrix(sum, firstMatrix.Rows, firstMatrix.Columns)
	End If

	Return Nothing
End Function
								


Example

									Dim m1 As Integer(,) = New Integer(1, 1) {}
m1(0, 0) = 8
m1(0, 1) = 6
m1(1, 0) = 7
m1(1, 1) = 5

Dim m2 As Integer(,) = New Integer(1, 1) {}
m2(0, 0) = 4
m2(0, 1) = 3
m2(1, 0) = 5
m2(1, 1) = 2

Dim matrix1 As New Matrix(m1, 2, 2)
Dim matrix2 As New Matrix(m2, 2, 2)
Dim sumMatrix As Matrix = SubtractMatrices(matrix1, matrix2)
								


Output

									(0, 0) = 4
(0, 1) = 3
(1, 0) = 2
(1, 1) = 3