Python program to Convert a Matrix to Sparse Matrix (original) (raw)

Last Updated : 15 Jan, 2025

Converting a matrix to a sparse matrix involves storing only non-zero elements along with their row and column indices to save memory.

Using a Dictionary

Converting a matrix to a sparse matrix using a dictionary involves storing only the non-zero elements of the matrix, with their row and column indices as keys and the corresponding values as dictionary values.

Python `

m = [ [1, 0, 0, 0], [0, 0, 3, 0], [0, 0, 0, 4] ]

sparse_matrix = {} for i in range(len(m)): for j in range(len(m[i])): if m[i][j] != 0: sparse_matrix[(i, j)] = m[i][j]

print(sparse_matrix)

`

Output

{(0, 0): 1, (1, 2): 3, (2, 3): 4}

**Explanation:

Using a List of Tuples

Converting a matrix to a sparse matrix using a list of tuples involves storing the non-zero elements as tuples where each tuple contains the row index, column index and the value. This method is efficient for representing sparse matrices while maintaining the order of the elements.

Python `

m = [ [1, 0, 0, 0], [0, 0, 3, 0], [0, 0, 0, 4] ]

sparse_matrix = [] for i in range(len(m)): for j in range(len(m[i])): if m[i][j] != 0: sparse_matrix.append((i, j, m[i][j]))

print(sparse_matrix)

`

Output

[(0, 0, 1), (1, 2, 3), (2, 3, 4)]

**Explanation:

Similar Reads