Learn-dsa..in 30 days!



























CC-12 : Check if matrix is an identity matrix.

Description:

An identity matrix is a matrix that has 1s in the diagonal indexes and 0s in all other indexes. Given input matrix mat, check if the matrix is an identity matrix.

Test cases and expected outputs:

Input Expected outputs
mat = {
{1,0,0},
{0,1,0},
{0,0,1}
};
The matrix is an Identity matrix.
mat = {
{0,1,0,0},
{0,1,0,0},
{0,0,1,0},};
The matrix is *not* an Identity matrix.
mat = {
{1,0},
{0,1},
{1,0},
{0,1}};
The matrix is *not* an Identity matrix.
mat = {
{0,1,0,0},
{0,1,0,0},
{0,0,1,0},
{0,0,0,2}};
The matrix is *not* an Identity matrix.

Pseudocode:

The java method should accept following input parameters: mat (integer matrix).
Only square matrices can be identity matrices. If number of rows of mat are not equal to number of columns, return false from the program.
Iterate through mat using a for loop, using variable rIdx as loop counter. Loop variable rIdx will be initialized with value 0 and will iterate through all the matrix’s columns one by one till rIdx < mat.length:
Iterate through mat using a for loop, using variable cIdx as loop counter. Loop variable cIdx will be initialized with value 0 and will iterate through all the matrix’s columns one by one till cIdx < mat[0].length:
If rIdx == cIdx, then check if mat[rIdx][cIdx]=1; it is not 1, the matrix is not an identity matrix, return false.
If rIdx != cIdx, then check if mat[rIdx][cIdx]=0; it is not 0, the matrix is not an identity matrix, return false.
If the above loops are completed and the program has not return false, it means the matric is an identity matrix, so return true.

Code:

public boolean matArrayIdentityMatrix(int[][] mat) throws Exception{
	if (mat.length != mat[0].length) { return false; }
	for (int rIdx=0; rIdx < mat.length; rIdx++) {
		for (int cIdx=0; cIdx < mat[0].length; cIdx++) {
		   if (rIdx==cIdx) {
			   if (mat[rIdx][cIdx] != 1) {
				   return false;
			   }
		   }else {
			   if (mat[rIdx][cIdx] != 0) {
				   return false;
			   }
		   }
		}
	}
	return true;
}

Click here to download and run code and test cases !