Default

Program to generate and print an identity matrix?

Program to generate and print an identity matrix?

An identity matrix is a square matrix of dimension n which contains ones along the principal diagonal and zeros in the rest of the other positions.

A 2×2 matrix is as follows:

1    0

0    1

4×4 Identity Matrix Example

For example, 4×4 matrix is shown below.

Identity Matrix 4x4

 

Java Program

Please note that Java does not have true multidimensional arrays. For instance, a two-dimensional array is implemented as an array of one-dimensional arrays.

Sample java program to generate and display a matrix of 6×6. It is a  straight forward program with two code blocks. The first code block fills the matrix. Fill logic populates with one if the row and column are the same.

The second code block displays the generated matrix.

Code Listing

public class IdentityMatrix {
    public static void main (String args[]) {
        int[][] imatrix;
        imatrix = new int[6][6];

        // fill the identity matrix
        for (int row=0; row < 6; row++) {
            for (int col=0; col < 6; col++) {
                if (row == col) {
                    imatrix[row][col]=1;
                }
                else {
                    imatrix[row][col] = 0;
                }
        }    }

        // print the identity matrix
        for (int row=0; row <6; row++) {
            for (int col=0; col < 6; col++)
                System.out.print(" " + imatrix[row][col] + " ");
            System.out.println();
        }
    }
}

 

Output of the program

1 0 0 0 0 0
0 1 0 0 0 0
0 0 1 0 0 0
0 0 0 1 0 0
0 0 0 0 1 0
0 0 0 0 0 1

 

Screenshot

Identiy matrix java program