[TOC]
Imports System
Imports CenterSpace.NMath.Core
Imports CenterSpace.NMath.Matrix
Namespace CenterSpace.NMath.Matrix.Examples.VisualBasic
' A .NET example in VB.NET demonstrating the features of the factorization classes for
' symmetric matrices.
Module SymFactExample
Sub Main()
' Construct a symmetric matrix as the product of the transpose of a
' matrix with itself.
Dim Rows As Integer = 5
Dim Cols As Integer = 5
Dim Rng As New RandGenUniform(-1, 1)
Rng.Reset(&H124)
Dim A As New DoubleMatrix(Rows, Cols, Rng)
Dim ATA As DoubleMatrix = NMathFunctions.TransposeProduct(A, A)
Dim S As New DoubleSymmetricMatrix(ATA)
Console.WriteLine()
Console.Write("S = ")
Console.WriteLine(A.ToString("F4"))
' S = 5x5 [ -0.4974 0.1821 0.5601 -0.2590 -0.8629
' 0.3315 -0.0443 0.3060 -0.9238 0.2029
' -0.2503 0.0738 0.2204 0.6206 -0.5848
' 0.5764 -0.3249 -0.0770 0.7734 0.6222
' 0.1961 -0.2797 -0.1678 0.3580 -0.7045 ]
' Construct a symmetric factorization class.
Dim Fact As New DoubleSymFact(S)
' Check to see if S is singular.
Dim IsSingularString As String
If Fact.IsSingular Then
IsSingularString = "S is singular"
Else
IsSingularString = "S is NOT singular"
End If
Console.WriteLine()
Console.WriteLine(IsSingularString)
' Retrieve information about the matrix S.
Dim Det As Double = Fact.Determinant()
Dim RCond As Double = Fact.ConditionNumber()
Dim SInv As DoubleSymmetricMatrix = Fact.Inverse()
Console.WriteLine()
Console.Write("Determinant of S = " & Det)
Console.WriteLine()
Console.Write("Reciprocal condition number = " & RCond)
Console.WriteLine()
Console.Write("S inverse = " & SInv.ToString())
' Use the factorization to solve some linear systems Ax = y.
Dim Y0 As New DoubleVector(Fact.Cols, Rng)
Dim Y1 As New DoubleVector(Fact.Cols, Rng)
Dim X0 As DoubleVector = Fact.Solve(Y0)
Dim X1 As DoubleVector = Fact.Solve(Y1)
Console.WriteLine()
Console.Write("Solution to Ax = y0 is ")
Console.WriteLine(X0.ToString())
Console.WriteLine()
Console.Write("y0 - Ax0 = ")
Console.WriteLine((Y0 - MatrixFunctions.Product(S, X0)).ToString())
Console.WriteLine()
Console.Write("Solution to Ax = y1 is ")
Console.WriteLine(X1.ToString())
Console.WriteLine()
Console.Write("y1 - Ax1 = ")
Console.WriteLine(DoubleVector.Subtract(Y1, MatrixFunctions.Product(S, X1)).ToString())
' You can also solve for multiple right-hand sides.
Dim Y As New DoubleMatrix(Y1.Length, 2)
Y.Col(0)(Slice.All) = Y0
Y.Col(1)(Slice.All) = Y1
Dim X As DoubleMatrix = Fact.Solve(Y)
' The first column of X should be x0 the second column should be x1.
Console.WriteLine()
Console.Write("X = ")
Console.WriteLine(X.ToString())
' Factor a different matrix.
Dim B As DoubleSymmetricMatrix = DoubleSymmetricMatrix.Multiply(1.2, S)
Fact.Factor(B)
X0 = Fact.Solve(Y0)
Console.WriteLine()
Console.Write("Solution to Bx = y0 is ")
Console.WriteLine(X0.ToString())
Console.WriteLine()
Console.WriteLine("Press Enter Key")
Console.Read()
End Sub
End Module
End Namespace
[TOC]