Add Matrices

This algorithm computes the sum 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 AddMatrices(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) = 1
m1(0, 1) = 2
m1(1, 0) = 3
m1(1, 1) = 4

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

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


Output

									(0, 0) = 6
(0, 1) = 8
(1, 0) = 5
(1, 1) = 5