In this article, we will understand how to determine if a given Matrix is a sparse matrix. A matrix is said to be sparse matrix if most of the elements of that matrix are 0. It implies that it contains very less non-zero elements.
Below is a demonstration of the same −
Suppose our input is −
Input matrix: 4 0 6 0 0 9 6 0 0
The desired output would be −
Yes, the matrix is a sparse matrix
Algorithm
Step 1 - START Step 2 - Declare an integer matrix namely input_matrix Step 3 - Define the values. Step 4 - Iterate over each element of the matrix using two for-loops, count the number of elements that have the value 0. Step 5 - If the zero elements is greater than half the total elements, It’s a sparse matrix, else its not. Step 6 - Display the result. Step 7 - Stop
Example 1
Here, we bind all the operations together under the ‘main’ function.
public class Sparse {
public static void main(String args[]) {
int input_matrix[][] = {
{ 4, 0, 6 },
{ 0, 0, 9 },
{ 6, 0, 0 }
};
System.out.println("The matrix is defined as: ");
int rows = 3;
int column = 3;
int counter = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < column; j++) {
System.out.print(input_matrix[i][j] + " ");
}
System.out.println();
}
for (int i = 0; i < rows; ++i)
for (int j = 0; j < column; ++j)
if (input_matrix[i][j] == 0)
++counter;
if (counter > ((rows * column) / 2))
System.out.println("\nYes, the matrix is a sparse matrix");
else
System.out.println("\nNo, the matrix is not a sparse matrix");
}
}Output
The matrix is defined as: 4 0 6 0 0 9 6 0 0 Yes, the matrix is a sparse matrix
Example 2
Here, we encapsulate the operations into functions exhibiting object-oriented programming.
public class Sparse {
static int rows = 3;
static int column = 3;
static void is_sparse(int input_matrix[][]){
int counter = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < column; j++) {
System.out.print(input_matrix[i][j] + " ");
}
System.out.println();
}
for (int i = 0; i < rows; ++i)
for (int j = 0; j < column; ++j)
if (input_matrix[i][j] == 0)
++counter;
if (counter > ((rows * column) / 2))
System.out.println("\nYes, the matrix is a sparse matrix");
else
System.out.println("\nNo, the matrix is not a sparse matrix");
}
public static void main(String args[]) {
int input_matrix[][] = { { 4, 0, 6 },
{ 0, 0, 9 },
{ 6, 0, 0 }
};
System.out.println("The matrix is defined as: ");
is_sparse(input_matrix);
}
}Output
The matrix is defined as: 4 0 6 0 0 9 6 0 0 Yes, the matrix is a sparse matrix