Trusted answers to developer questions

How to check if a given matrix is an identity matrix

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

Problem overview

Given a matrix, check if it’s an identity matrix.

Example 1:

{{1,0,0},
 {0,1,0},
 {0,0,1}}

The matrix above is an identity matrix.

Example 2:

{{1,4,3},
 {9,1,0},
 {0,0,1}}

The matrix above is not an identity matrix.

What is an identity matrix?

A matrix is called an identity matrix or a unit matrix if the principal diagonal elementsthe elements from the upper left corner to the bottom right corner along the diagonal are all ones and other elements in the matrix are zero.

For example:

{{1,0,0},
 {0,1,0},
 {0,0,1}}

The example above is a 3x3 identity matrix.

Algorithm

  1. Start looping over the elements of the matrix.
  2. For every element, check the following:
    1. If the row number is equal to the column number, then it’s a diagonal element. Check if the value is one.
    2. If the row number is not equal to the column number, then it’s not a diagonal element. Check if the value is zero.
    3. If any of the above conditions are false, then the matrix is not an identity matrix. Return false.
    4. Otherwise, return true, indicating that the matrix is an identity matrix.

Code

public class Main{
private static boolean checkIdentityMatrix(int[][] matrix){
for(int i=0; i<matrix.length;i++)
for(int j=0; j<matrix[i].length;j++){
if((i == j && matrix[i][j] != 1) || (i != j && matrix[i][j] != 0)) return false;
}
return true;
}
public static void main(String[] args){
int[][] matrix = {{1,0,0},
{0,1,9},
{0,0,1}};
if(checkIdentityMatrix(matrix)) System.out.println("The matrix is an identity matrix");
else System.out.println("The matrix is not an identity matrix");
}
}

In the code above, we check if the following matrix is an identity matrix.

{{1,0,0},
 {0,1,9},
 {0,0,1}}

As the element at the second row and third column is not zero, it’s not an identity matrix.

RELATED TAGS

java
identity
matrix
Did you find this helpful?