Python program to Convert a Matrix to Sparse Matrix

Python program to Convert a Matrix to Sparse Matrix

A sparse matrix is a matrix in which most of the elements are zero (or, in general, any specific default value). Representing a sparse matrix in its full form can be memory inefficient, so a common approach is to represent it using a list of non-default values along with their location in the matrix.

The following tutorial demonstrates how to convert a regular matrix (2D list) to a sparse matrix representation in Python:

Approach:

  1. Iterate over each element of the matrix.
  2. For non-zero elements (or elements not equal to the default value), store its value along with its row and column indices.
  3. Return the sparse matrix representation as a list of tuples, where each tuple is of the form (row_index, col_index, value).

Python Program:

def convert_to_sparse(matrix): """Convert a 2D matrix to its sparse representation.""" sparse_representation = [] for i in range(len(matrix)): for j in range(len(matrix[i])): if matrix[i][j] != 0: # Change this condition if default value is different sparse_representation.append((i, j, matrix[i][j])) return sparse_representation # Testing the function matrix = [ [5, 0, 0, 0], [0, 8, 0, 0], [0, 0, 3, 0], [0, 6, 0, 0] ] print(f"Sparse Representation: {convert_to_sparse(matrix)}") 

Output:

Sparse Representation: [(0, 0, 5), (1, 1, 8), (2, 2, 3), (3, 1, 6)] 

Explanation:

  • The function convert_to_sparse iterates over each element in the provided matrix.
  • For each non-zero element, it adds a tuple to the sparse representation list with the row index, column index, and the value.
  • The sparse matrix representation contains only the non-zero values along with their positions.

This sparse representation reduces the memory required to store the matrix when most of its elements are zero (or a specific default value). If needed, you can easily extend this approach to handle other default values besides zero.


More Tags

kendo-chart flat mpandroidchart decoder ionicons android-manifest jquery-cookie cubemx cpu-registers invisible

More Programming Guides

Other Guides

More Programming Examples