Trusted answers to developer questions

abhilash

Given the number of rows and columns, generate a 2D identity matrix for the given dimensions.

Example 1:

- Input -
`(3, 3)`

- Output Matrix

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

- Input -
`(3, 4)`

- Output -
`Cannot generate an identity matrix as the given dimensions are not equal`

.

An identity matrix or a unit matrix is a square matrix that has principal diagonal elements. This means that the elements from the upper left corner to the bottom right corner along the diagonal are `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.

- Check if the given dimensions are equal. If the dimensions are not equal, then an identity matrix canâ€™t be generated
- Create a 2D matrix with the given dimensions
- Run two loops. One loop is iterating along the rows, and the other loop is iterating along the columns. During the iteration, execute the following steps
- When the row number is equal to the column number, set the element at that location to
`1`

- When the row number is not equal to the column number, set the element at that location to
`0`

.

- When the row number is equal to the column number, set the element at that location to

The pseudo-code is as follows:

```
1. if numRows != numCols then print("Can't Generate Matrix") return;
2. Define matrix[numRows][numCols]
3. for i from 0 to numRows-1
do
for j from 0 to numCols-1
do
if i equal to j then
set matrix[i][j] = 1
else
set matrix[i][j] = 0
done
done
```

i=0, j=0; i == j; Hence, set the value to 1

import java.util.Arrays; public class Main{ private static int[][] generateIdentityMatrix(int numRows, int numCols){ int[][] identityMatrix = new int[numRows][numCols]; for(int i=0; i < numRows;i++) for(int j=0; j < numRows;j++){ if(i == j) identityMatrix[i][j] = 1; else identityMatrix[i][j] = 0; } return identityMatrix; } private static void printMatrix(int[][] matrix){ for (int[] row : matrix) System.out.println(Arrays.toString(row)); } public static void main(String[] args){ int numRows = 3; int numCols = 3; if(numRows != numCols){ System.out.println("Cannot generate an identity matrix as the given dimensions are not equal"); } else{ int[][] identityMatrix = generateIdentityMatrix(numRows, numCols); System.out.printf("The generated matrix for the (%d, %d) dimension is - \n", numRows, numCols); printMatrix(identityMatrix); } } }

RELATED TAGS

data structures

matrix

identity matrix

communitycreator

CONTRIBUTOR

abhilash

RELATED COURSES

View all Courses

Keep Exploring

Related Courses