← All NMath Code Examples
Imports CenterSpace.NMath.Core
Namespace CenterSpace.NMath.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)()
Values.Add(New IntPair(0, 0), 7)
Values.Add(New IntPair(0, 2), 1)
Values.Add(New IntPair(0, 5), 2)
Values.Add(New IntPair(0, 6), 7)
Values.Add(New IntPair(1, 1), -4)
Values.Add(New IntPair(1, 2), 8)
Values.Add(New IntPair(1, 4), 2)
Values.Add(New IntPair(2, 2), 1)
Values.Add(New IntPair(2, 7), 5)
Values.Add(New IntPair(3, 3), 7)
Values.Add(New IntPair(3, 6), 9)
Values.Add(New IntPair(4, 4), 5)
Values.Add(New IntPair(4, 5), 1)
Values.Add(New IntPair(4, 6), 5)
Values.Add(New IntPair(5, 5), -1)
Values.Add(New IntPair(5, 7), 5)
Values.Add(New IntPair(6, 6), 11)
Values.Add(New IntPair(7, 7), 5)
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")
Console.Read()
End Sub
End Module
End Namespace
← All NMath Code Examples