VB Vector 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
  ' vector/vector and vector/scalar operations.
  '
  ' The arithmetic operators +,-,*,/ are overloaded
  ' for vector-vector and vector-scalar operations. These operators
  ' have their usual meanings. For example, if u, v, and w are
  ' vectors, s is a scalar and op is one of +,-,*,/, then
  ' 
  '   w = u op v
  '   
  ' produces a vector w such that
  ' 
  '   w[i] = u[i] op v[i]
  '   
  ' and 
  ' 
  '   w = s op v
  '   
  ' produces a vector w such that
  ' 
  '   w[i] = s op v[i].
  Module VectorArithmeticExample

    Sub Main()

      Dim length As Integer = 5

      Console.WriteLine()

      ' Create two vectors v1 and v2. v1 alternates values 1, 0, 1,...
      ' and v2 alternates values 0, 1, 0,...
      Dim v1 As New FloatVector(length)
      Dim v2 As New FloatVector(length)
      Dim everyOther As New Range(0, Position.End, 2)
      v1.Set(everyOther, 1)
      everyOther.Set(1, Position.End, 2)
      v2.Set(everyOther, 1)
      Console.WriteLine("v1 = {0}", v1.ToString())   ' v1 = [1 0 1 0 1]
      Console.WriteLine("v2 = {0}", v2.ToString())   ' v2 = [0 1 0 1 0]

      ' Summing v1 and v2 will yield a vector of all 1's.
      Dim sum As FloatVector = v1 + v2
      Console.WriteLine("v1 + v2 = {0}", sum.ToString())   ' v1 + v2 = [1 1 1 1 1]

      ' Vector scalar operators are also provided.
      Dim a As Single = 2
      Dim asum As FloatVector = v1 + (a * v2)
      Console.WriteLine("v1 + a*v2 = {0}", asum.ToString())   ' v1 + a*v2 = [1 2 1 2 1]

      ' If we increase the length of v1 and try to multiply with v2, we
      ' will get a MismatchedSizeException. Vectors must have the same
      ' length to be combined using the element-wise operators.
      v1.Resize(length + 1)
      Dim product As FloatVector
      Try
        product = v1 * v2
      Catch e As MismatchedSizeException
        Console.WriteLine("Oops - " + e.Message)
      End Try

      ' Increment and decrement operators have been overloaded too.
      Console.WriteLine("v2 = {0}", v2.ToString())
      v2 = FloatVector.Increment(v2)
      Console.WriteLine("v2++ = {0}", v2.ToString())

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

    End Sub

  End Module

End Namespace

← All NMath Code Examples
Top