Trusted answers to developer questions

abhilash

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.

A matrix is called an **identity matrix** or a *unit matrix* if the `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.

- Start looping over the elements of the matrix.
- For every element, check the following:
- If the row number is equal to the column number, then it’s a diagonal element. Check if the value is
`one`

. - If the row number is not equal to the column number, then it’s not a diagonal element. Check if the value is
`zero`

. - If any of the above conditions are
`false`

, then the matrix is not an identity matrix. Return`false`

. - Otherwise, return
`true`

, indicating that the matrix is an identity matrix.

- If the row number is equal to the column number, then it’s a diagonal element. Check if the value is

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

communitycreator

CONTRIBUTOR

abhilash

RELATED COURSES

View all Courses

Keep Exploring

Related Courses