# Convert a Matrix to a Sparse Matrix in Python

To covert the matrix into the sparse matrix in Python we first need to understand what is sparse matrix and why it is used. So here we will learn about it and along with it, we will have a look at the algorithm and then code for the conversion of the matrix to a sparse matrix.

**Sparse Matrix:**

- Sparse Matrix is memory-efficient. It enables us to store large matrices that have most of its elements 0.
- Moreover, it also makes it easy for us to perform computational complex matrix problems. For example, if a programmer wants to perform multiplication or inversion, a sparse matrix format is more efficient.
- In the sparse matrix, we use to represent each non-zero value present in the matrix in the form of
**Row Column Value.**

Example:

Matrix:

1 0 0 0 0 0 2 0 0 3 0 0 0 0 0 4

Sparse Matrix:

0 0 1 1 2 2 2 1 3 3 3 4

Here 1 is written as 0 0 1 that denotes row-0 and column-0. 2 is written as 1 2 2 that denotes row-1, and column-2 similarly about other non-zero elements of the matrix.

## Converting matrix to sparse matrix in Python

**Algorithm:**

- Firstly, create an empty list(sparse matrix list).
- Then find the non-zero elements in the matrix by iterating the whole matrix.
- After that, if you find a non-zero element, create a temporary empty list and append details of the non-zero element in it(row, column and element).
- Append temporary list to sparse matrix created.
- Lastly, we got our sparse matrix with non-zero elements of the matrix.

**Code:**

def matrix_to_sparse(matrix): sparse_matrix=[] #Search non-zero elements for i in range(len(matrix)): for j in range(len(matrix[0])): if matrix[i][j]!=0: #temporary list temp=[] temp.append(i) temp.append(j) temp.append(matrix[i][j]) sparse_matrix.append(temp) #returning final sparse matrix list return sparse_matrix #input matrix matrix=[[0,2,0,5], [0,0,1,0], [0,2,0,0], [0,0,0,3]] #function calling to convert matrix to sparse matrix sparse_matrix=convert_to_sparse(matrix) #printing sparse matrix print("Sparse Matrix:") for i in sparse_matrix: for j in i: print(j,end=' ') print()

Output:

Sparse Matrix: 0 1 2 0 3 5 1 2 1 2 1 2 3 3 3

In conclusion, using a sparse matrix over the normal matrix is an efficient way, and also the conversion of the matrix to a sparse matrix is not hard.

## Leave a Reply