# VB Sparse Matrix Example

← All NMath Code Examples

```ï»¿Imports System.IO
Imports System.Globalization

Imports CenterSpace.NMath.Core
Imports CenterSpace.NMath.Matrix

Namespace CenterSpace.NMath.Matrix.Examples.VisualBasic

' A .NET example in Visual Basic showing simple general sparse matrix functionality.
Module SparseMatrixExample

Sub Main()

Console.WriteLine()

Dim A As DoubleComplexCsrSparseMatrix = ReadComplexMtxFile()
Console.WriteLine("A is a {0}x{1} complex-valued sparse matrix with {2} nonzero entries", A.Rows, A.Cols, A.Data.NumberNonZero)
Dim AHA As DoubleComplexCsrSparseMatrix = MatrixFunctions.ConjTransposeProduct(A, A)
Console.WriteLine("The conjugate transpose product of A with itself has {0} nonzero entries.", AHA.Data.NumberNonZero)
Dim V As DoubleComplexVector = New DoubleComplexVector(A.Cols, 1)
Dim Av As DoubleComplexVector = MatrixFunctions.Product(A, V)
Console.WriteLine("The product of a with a dense vector, v, has length {0}", Av.Length)

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

Dim Delimiters(1) As Char
Delimiters = New Char() {" "}
Dim LineCount As Integer = 0
Dim Rows As Integer = 0
Dim Cols As Integer = 0
Dim NumberNonzero = 0

While (Line.Contains("%"))
End While

Dim CoordValues As New Dictionary(Of IntPair, DoubleComplex)
While (True)
If (Line Is Nothing) Then
Exit While
End If

If (LineCount = 0) Then
' First non-comment, read rows, columns, and number nonzero
Dim MatrixInfo() As String = Line.Split(Delimiters, StringSplitOptions.RemoveEmptyEntries)
If (MatrixInfo.Length <> 3) Then
Throw New Exception("Invalid MTX file")
End If
Rows = Int32.Parse(MatrixInfo(0))
Cols = Int32.Parse(MatrixInfo(1))
NumberNonzero = Int32.Parse(MatrixInfo(2))

Else

' Line should have 4 entries, a row index, a column index, real and imaginary
' parts of the value.
Dim RowColValue() As String = Line.Split(Delimiters, StringSplitOptions.RemoveEmptyEntries)
If (RowColValue.Length <> 4) Then
Throw New Exception("Invalid MTX file" + Line)
End If
Dim Row As Integer = Int32.Parse(RowColValue(0)) - 1 ' mtx files use one-based indexing.
Dim Col As Integer = Int32.Parse(RowColValue(1)) - 1
Dim Re As Double = Double.Parse(RowColValue(2))
Dim Im As Double = Double.Parse(RowColValue(3))
CoordValues.Add(New IntPair(Row, Col), New DoubleComplex(Re, Im))
End If

LineCount = LineCount + 1