Print An Identity Matrix In Python

In this tutorial, we will learn how to print an identity matrix in python. The size of the matrix is user inputted. We will be using the following concepts to print the identity matrix:

  • Python if…else Statement
  • Loops in python

Identity Matrix

An identity matrix is a square matrix with all diagonal elements as 1 and all other elements as 0. The size of the matrix is also known as the order of the matrix. The identity matrix have ample applications in mathematics. You can read more about the identity matrix here.

#Taking input from user
order = int(input("Enter order of matrix: "))

#Starting loop for rows
for i in range(0, order):
    #Starting loop for columns
    for j in range(0, order):
        #Diagonal element check
        if i == j :
            print("1", end = " ")
            print("0", end = " ")

First, we ask the user to input the order of the matrix using int(input(“Enter order of matrix: “)). Here, input() prints the message on the console and also reads the input given as a string. But we want the input to be an int so that we can perform mathematical operations on them and for that, we use int().

We then start nested loops to print the matrix pattern. The first loop is used to print the number of rows. Inside this loop, we start another loop that represents columns in every row. Inside this loop, we check if it is a diagonal element using i == j. If they are equal then we print a 1. If not then we print a 0. We print an empty line using print() after the completion of loop so that we move to the next row.


Enter order of matrix: 3
1 0 0
0 1 0
0 0 1

Enter order of matrix: 5
1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1

So, here it is a simple program to print an identity matrix of any order in python.

Also read,

Create a matrix of random numbers in Python using NumPy

Perform Matrix Multiplication of given dimension in Python

Matrix Transpose of a given Matrix of any dimension in Python3

Leave a Reply

Your email address will not be published. Required fields are marked *