← All NMath Code Examples
Imports System
Imports CenterSpace.NMath.Core
Imports Range = CenterSpace.NMath.Core.Range
Namespace CenterSpace.NMath.Examples.VisualBasic
A .NET example in Visual Basic showing how to use the indexing class Range with the matrix classes.
Module MatrixRangeExample
Sub Main()
Dim rows As Integer = 5
Dim cols As Integer = 5
Dim A As New DoubleMatrix(rows, cols, 0, 1)
| 0 5 10 15 20 |
| 1 6 11 16 21 |
A = | 2 7 12 17 22 |
| 3 8 13 18 23 |
| 4 9 14 19 24 |
Console.WriteLine()
Console.WriteLine("A...")
Console.WriteLine(A.ToTabDelimited())
Console.WriteLine()
Last two columns of the matrix A:
Dim colRange As New Range(3, 4)
Dim rowRange As Range = Range.All
Dim ALast2Col As DoubleMatrix = A(rowRange, colRange)
| 15 20 |
| 16 21 |
ALast2Col = | 17 22 |
| 18 23 |
| 19 24 |
Console.WriteLine("ALast2Col...")
Console.WriteLine(ALast2Col.ToTabDelimited)
Console.WriteLine()
Could also get this by specifying all elements from the 4th column
to the end using the End value from the enum
CenterSpace.NMath.Core.Position
ALast2Col = A(rowRange, New Range(3, Position.End))
Console.WriteLine("ALast2Col...")
Console.WriteLine(ALast2Col.ToTabDelimited)
Console.WriteLine()
You can use negative strides too. Here is the matrix A, reversed.
We re-use the Range objects, setting their start, stop, and stride
fields using the Set method.
rowRange = New Range(rows - 1, 0, -1)
colRange.Set(cols - 1, 0, -1)
Dim ARev As DoubleMatrix = A(rowRange, colRange)
| 24 19 14 9 4 |
| 23 18 13 8 3 |
ARev = | 22 17 12 7 2 |
| 21 16 11 6 1 |
| 20 15 10 5 0 |
Console.WriteLine("ARev...")
Console.WriteLine(ARev.ToTabDelimited)
Console.WriteLine()
Notice that when you create a new DoubleMatrix using the Range or Slice class,
you are creating a different "view" of the Matrix data. That is, the
DoubleMatrix instance returned by the indexing operator taking a Range object,
and the DoubleMatrix instance being indexed share the same data:
ARev(0, 0) = 100
Console.WriteLine("ARev[0,0] = {0}", ARev(0, 0)) uRev = [0 8 7 6 5 4 3 2 1 0]
Console.WriteLine()
Console.WriteLine("A[{0},{1}] = {2}", rows - 1, cols - 1, A(rows - 1, cols - 1)) A[4,4]
Console.WriteLine()
We now use the DoubleMatrix method Set(Range,Range,value) to change the
contents of A to alternate values 0 and 1 - like a checker board.
Dim evenElts As New Range(0, Position.End, 2)
Dim oddElts As New Range(1, Position.End, 2)
A.Set(evenElts, oddElts, 0)
A.Set(evenElts, evenElts, 1)
A.Set(oddElts, evenElts, 0)
A.Set(oddElts, oddElts, 1)
| 1 0 1 0 1 |
| 0 1 0 1 0 |
A = | 1 0 1 0 1 |
| 0 1 0 1 0 |
| 1 0 1 0 1 |
Console.WriteLine("A...")
Console.WriteLine(A.ToTabDelimited)
Console.WriteLine()
Console.WriteLine("Press Enter Key")
Console.Read()
End Sub
End Module
End Namespace
← All NMath Code Examples