Given a matrix with most of its elements as 0, we need to convert this matrix into a sparse matrix in Python.
1 0 0 0
0 2 0 0
0 0 3 0
0 0 0 4
5 0 0 0
Output: Sparse Matrix:
0 0 1
1 1 2
2 2 3
3 3 4
4 0 5
Here the Matrix is represented using a 2D list and the Sparse Matrix is represented in the form Row Column Value
In the Sparse Matrix the first row is
0 1 1indicates that the value of the Matrix at row 0 and column 1 is 1.
- Create an empty list which will represent the sparse matrix list.
- Iterate through the 2D matrix to find non zero elements.
- If an element is non zero, create a temporary empty list.
- Append the row value, column value, and the non zero element itself into the temporary list.
- Now append the temporary list into the sparse matrix list such that the temporary list acts as a sub-list of the sparse matrix list.
- After getting all the non zero elements from the matrix, display the sparse matrix.
The above approach has been used in
convertToSparseMatrix() function in the below program:
0 1 0 0 0 0 2 0 0 3 0 0 0 0 5 0 0 0 0 4 Sparse Matrix: 0 0 1 1 1 2 2 2 3 3 3 4 4 0 5
- How To Visualize Sparse Matrix in Python using Matplotlib?
- Python - Convert Matrix to Custom Tuple Matrix
- Python - Convert Matrix to dictionary
- Python - Convert Strings to Character Matrix
- Python - Convert Coordinate Dictionary to Matrix
- Python - Convert Matrix to Coordinate Dictionary
- Python | Convert Character Matrix to single String
- Python - Convert Matrix to overlapping Tuple Pairs
- Python Program for Program to Print Matrix in Z form
- Python Program to find transpose of a matrix
- Python Program for Matrix Chain Multiplication | DP-8
- Python Program for Maximum size square sub-matrix with all 1s
- Python program to search for the minimum element occurring consecutively n times in a matrix
- Create an n x n square matrix, where all the sub-matrix have the sum of opposite corner elements as even
- Python | Numpy matrix.ptp()
- Python - Check for None value in Matrix
- Python | Numpy matrix.put()
- Python | Numpy matrix.max()
- Python | Numpy matrix.dot()
- Python | Get Kth Column of Matrix
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.