How to reconstruct a full sparse matrix from a compact (triplet) matrix in Python

1 Answer

0 votes
# A sparse matrix is a matrix in which the majority of elements are zero.

# To rebuild a sparse matrix from a compact (triplet) representation,
# we create a full matrix initialized with zeros, then place each
# non‑zero element at its (row, column) position.

# Build full sparse matrix from compact triplet form
def build_sparse_from_compact(compact, count):

    row_idx = compact[0]
    col_idx = compact[1]
    values = compact[2]

    # Determine matrix dimensions automatically
    max_row = 0
    max_col = 0

    for i in range(count):
        if row_idx[i] > max_row:
            max_row = row_idx[i]
        if col_idx[i] > max_col:
            max_col = col_idx[i]

    rows = max_row + 1
    cols = max_col + 1

    # Create full matrix initialized with zeros
    sparse = [[0 for _ in range(cols)] for _ in range(rows)]

    # Fill matrix
    for i in range(count):
        sparse[row_idx[i]][col_idx[i]] = values[i]

    return sparse


# Print a matrix
def print_matrix(mat, title):
    print(title)
    for row in mat:
        print(" ".join(str(x) for x in row))
    print()


def main():

    # 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

    compact = [
        [0, 0, 1, 1, 1, 3, 3, 3, 4],  # row indices
        [2, 4, 2, 3, 6, 1, 2, 5, 4],  # column indices
        [3, 8, 5, 7, 1, 2, 6, 4, 9]   # values
    ]

    count = 9

    print("Compact matrix:")
    for i in range(3):
        print(" ".join(str(compact[i][j]) for j in range(count)))
    print()

    sparse = build_sparse_from_compact(compact, count)

    print_matrix(sparse, "Sparse matrix (auto-sized):")


if __name__ == "__main__":
    main()



"""
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

Sparse matrix (auto-sized):
0 0 3 0 8 0 0
0 0 5 7 0 0 1
0 0 0 0 0 0 0
0 2 6 0 0 4 0
0 0 0 0 9 0 0

"""

 



answered 2 hours ago by avibootz

Related questions

...