# VB Sparse Factorization Example

← All NMath Code Examples

```ï»¿Imports CenterSpace.NMath.Core
Imports CenterSpace.NMath.Matrix

Namespace CenterSpace.NMath.Matrix.Examples.VisualBasic

' A .NET example in Visual Basic showing how to solve a symmetric sparse linear system using the
' DoubleSparseSymFact class.
Module SparseFactorizationExample

Sub Main()

Dim Values As New Dictionary(Of IntPair, Double)()

' Create a symmetric sparse matrix with 8 columns from the above data.
Dim S As New DoubleSymCsrSparseMatrix(Values, 8)

' Factor the matrix. The factorization can then be used to solve for various
' right hand sides.
Dim Fact As New DoubleSparseSymFact(S)

Console.WriteLine()

' Check that factorization succeeded.
If (Fact.ErrorStatus <> SparseMatrixFact(Of Double).Error.NoError) Then
Console.WriteLine("Error {0} in factoring sparse matrix S. " & Fact.ErrorStatus)
Return
End If

' Right hand side a vector containing all ones.
Dim B As New DoubleVector(8, 1)
Dim X As DoubleVector = Fact.Solve(B)

' Check that solve succeeded.
If (Fact.ErrorStatus <> SparseMatrixFact(Of Double).Error.NoError) Then
Console.WriteLine("Error {0} in solving sparse system Sx = b. " & Fact.ErrorStatus)
Return
End If

Console.WriteLine("Solution for one right hand side = ")
Console.WriteLine(X.ToString("G5"))

' Solve for several right hand sides.
Dim nrhs As Integer = 3
Dim B2 As New DoubleMatrix(8, nrhs, New RandGenBeta())
Dim X2 As DoubleMatrix = Fact.Solve(B2)

' Check that solve succeeded.
If (Fact.ErrorStatus <> SparseMatrixFact(Of Double).Error.NoError) Then
Console.WriteLine("Error {0} in solving sparse system Sx = b. " & Fact.ErrorStatus)
Return
End If

Console.WriteLine(Environment.NewLine & "Solving for {0} right hand sides.", nrhs)
Dim I As Integer = 0
For I = 0 To (nrhs - 1)
Console.WriteLine()
Console.WriteLine("Solution for rhs")
Console.WriteLine(B2.Col(I).ToString("G5"))
Console.WriteLine("is")
Console.WriteLine(X2.Col(I).ToString("G5"))
Next

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

End Sub
End Module
End Namespace

```
← All NMath Code Examples
Top