# VB Matrix Arithmetic Example

← All NMath Code Examples

```Imports System

Imports CenterSpace.NMath.Core

Namespace CenterSpace.NMath.Core.Examples.VisualBasic

' A .NET example in Visual Basic showing the element-wise operators overloaded for
' matrix/matrix and matrix/scalar operations.
'
' The arithmetic operators +,-,*,/ are overloaded
' for matrix-matrix and matrix-scalar operations. These operators
' have their usual meanings. For example, if A, B, and C are
' matrices, s is a scalar and op is one of +,-,*,/, then
'
'   C = A op B
'
' produces a matrix C such that
'
'   C[i,j] = A[i,j] op B[i,j]
'
' and
'
'   C = s op B
'
' produces a matrix C such that
'
'   C[i,j] = s op B[i,j].
Module MatrixArithmeticExample

Sub Main()

Console.WriteLine()

Dim rows As Integer = 3
Dim cols As Integer = 3

' Create a matrix containing all (1,0)'s
Dim A As New DoubleComplexMatrix(rows, cols, New DoubleComplex(1, 0))
' Create a matrix containing all (0,1)'s
Dim B As New DoubleComplexMatrix(rows, cols, New DoubleComplex(0, 1))
Console.WriteLine("A = {0}", A.ToString())
Console.WriteLine("B = {0}", B.ToString())

' Adding them together will yield a matrix of the same size containing
' all (1,1)'s
Dim S As DoubleComplexMatrix = A + B
Console.WriteLine("A + B = {0}", S.ToString())

' Vector scalar operators are also provided.
Dim c As New DoubleComplex(2, 0)

' Produces a matrix containing all (1,2)'s
Dim aSum As DoubleComplexMatrix = A + (c * B)
Console.WriteLine("A + c*B = {0}", aSum.ToString())

' If we increase the number of rows of A and try to multiply with B, we
' will get a MismatchedSizeException. Matrices must have the same
' dimensions to be combined using the element-wise operators.
A.Resize(rows + 1, cols)
Dim P As DoubleComplexMatrix
Try
P = A * B
Catch e As MismatchedSizeException
Console.WriteLine("Oops - " + e.Message)
End Try

' Put A back the way it was.
A.Resize(rows, cols)

' Increment and decrement operators have been overloaded too
' (for real types only).
Dim Areal As DoubleMatrix = NMathFunctions.Real(A)
Console.WriteLine("Areal = {0}", Areal.ToString())
Areal = DoubleMatrix.Increment(Areal)
Console.WriteLine("Areal++ = {0}", Areal.ToString())

Console.WriteLine()
Console.WriteLine("Press Enter Key")