How to compact a sparse matrix in VB.NET

1 Answer

0 votes
Imports System

Module SparseMatrixModule

    ' A sparse matrix is a matrix in which the majority of elements are zero.

    ' To compact a sparse matrix, use a method to store only the non‑zero
    ' entries using a triplet representation (row, column, value). 
    ' This reduces memory usage.

    ' Convert a sparse matrix into compact (triplet) form
    Function CompactMatrix(matrix As Integer(,)) As Integer(,)
        Dim rows As Integer = matrix.GetLength(0)
        Dim cols As Integer = matrix.GetLength(1)

        ' Count non-zero elements
        Dim count As Integer = 0
        For i As Integer = 0 To rows - 1
            For j As Integer = 0 To cols - 1
                If matrix(i, j) <> 0 Then
                    count += 1
                End If
            Next
        Next

        ' Compact matrix has 3 rows: row index, col index, value
        Dim compact(2, count - 1) As Integer

        Dim k As Integer = 0

        ' Fill compact matrix
        For i As Integer = 0 To rows - 1
            For j As Integer = 0 To cols - 1
                If matrix(i, j) <> 0 Then
                    compact(0, k) = i              ' row
                    compact(1, k) = j              ' column
                    compact(2, k) = matrix(i, j)   ' value
                    k += 1
                End If
            Next
        Next

        Return compact
    End Function

    Sub Main()
        Dim matrix As Integer(,) = {
            {0, 0, 3, 0, 8, 0, 0, 0, 0},
            {0, 0, 5, 7, 0, 0, 1, 0, 0},
            {0, 0, 0, 0, 0, 0, 0, 0, 0},
            {0, 2, 6, 0, 0, 4, 0, 0, 0},
            {0, 0, 0, 0, 9, 0, 0, 0, 0}
        }

        Dim compact = CompactMatrix(matrix)

        Console.WriteLine("Compact matrix:")
        For i As Integer = 0 To 2
            For j As Integer = 0 To compact.GetLength(1) - 1
                Console.Write(compact(i, j) & " ")
            Next
            Console.WriteLine()
        Next

        Console.WriteLine()
        Console.WriteLine("Press any key to exit...")
        Console.ReadKey()
    End Sub

End Module


' run:
'
' Compact matrix:
' 0 0 1 1 1 3 3 3 4 
' 2 4 2 3 6 1 2 5 4 
' 3 8 5 7 1 2 6 4 9 
'

 



answered 1 day ago by avibootz
edited 1 day ago by avibootz
...