Python Program to display an identity matrix


April 21, 2022, Learn eTutorial
1306

In this simple python program, we need to print an identity matrix. It's a matrix python program.

To understand this example, you should have knowledge of the following Python programming topics:

What is an identity matrix?

In this simple python program on matrix, we have to display an Identity Matrix. The identity matrix is a square matrix of any order in which the elements in the principal diagonal matrix are ones, and all other elements in the matrix are zeros. In this matrix python program, we need to print an identity matrix in which the user enters the order. A diagonal matrix can be represented as  A =

[ 1 0 0 ]

[ 0 1 0 ]

[ 0 0 1 ]

We check the diagonal has the ones, and all other elements are zeros.

How we print an identity matrix in python?

For applying the identity matrix logic in this python program, we accept the order of matrix from the user, and we use two nested for loops in python for iterating through rows and columns in the matrix. The row number and column number must be the same for the diagonal values in the identity matrix. like matrix[1, 1] [2 , 2] [3 , 3]. So we have to check the condition i = j  using an if condition in python and print one if the condition satisfies. Else we print zero. After all, for loop iterations, We print the identity matrix.

ALGORITHM

STEP 1: Accept the order from the user using the input method and convert the string to an integer using int() in the Python programming language.

STEP 2: Use the outer for loop from zero to n for iterations through the matrix's rows. 

STEP 3: Use the inner for loop to iterate through the columns of each row of the matrix.

STEP 4: Check using an 'if condition' that 'i = j' and print 1 if the condition satisfies.

STEP 5: Print zero in the positions if the condition fails. using python basic syntax.

Note: We use the sep parameter for printing the separator value and use 'end=' to append the values using the print statement.

Python Source Code

                                          n=int(input("Enter a number: "))
for i in range(0,n):
    for j in range(0,n):
        if(i==j):
            print("1",sep=" ",end=" ")
        else:
            print("0",sep=" ",end=" ")
    print()
                                      

OUTPUT

Enter a number: 4
1 0 0 0 
0 1 0 0 
0 0 1 0 
0 0 0 1