Check whether a matrix is sparse matrix or not in Python
In this tutorial, we will discuss the matrix and check if it is a sparse matrix or not.
A matrix is a grid of rows and columns consisting of 0’s and 1’s. A matrix of 3*3 looks like this-
1 2 3 4 5 6 7 8 9
A sparse matrix is a matrix where more than half of the elements are zero.
Example of a sparse matrix-
0 2 5 3 0 0 0 3 0
Here there are 5 zeroes which are more than half of the total elements.
Now we will declare an array of 9 elements of the dimension 3*3 and count as 0. Initializing loop and a nested for loop to check for all the elements and increase the count by 1 if the element is 0 and then we will print bool value if count is greater than half of the elements.
a=[[1, 2, 4],
[0, 0, 0],
[4, 0, 0]]
m=3
n=3
count=0
for i in range(0,m):
for j in range(0,n):
if (a[i][j]==0):
count+=1
print(count>(m*n)//2)True
So here we have accomplished the task to check if the matrix is sparse or not.
Leave a Reply