Python program to print one identity matrix

Python program to print an identity matrix :

In this tutorial,we will learn how to print a identity matrix in python. A matrix is called identity matrix if all of its digonal elements from upper left corner to bottom right corner is 1 and all other elements are 0. For example, following matrix are identity matrix :

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

1 0
0 1

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

In our program, we will ask the user to enter the size of the matrix and then we will print the identity matrix . Let’s take a look at the program :

Python program to print an identity matrix :

#1
size = int(input("Enter the size of the matrix : "))

#2
for i in range(0,size):
	#3
	for j in range(0,size):
		#4
		if(i==j):
			print("1",end = " ")
		else:
			print("0",end = " ")
	#5
	print()

Explanation :

The main idea behind printing a identity matrix is that the its value will be equal to 1 if current row number is equal to the current column number. For first row, matrix[0][0] is 1, for the second row, matrix[1][1] is 1 etc. So, to print the matrix, we will use two for loops and if both the counters of both for loops is same, print 1 . Else, print 0.

The commented numbers in the above program denote the step number below :

1. Ask the user to enter the size of the matrix and save it in variable size.
2. Run one for loop from 0 to size of the matrix – 1.
3. Start one more inner for loop and run it from 0 to size of the matrix – 1.
4. Check if i is equal to j or not. If yes, print 1 , else print 0.
5. Print one new line.

Sample Output :

Enter the size of the 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

Enter the size of the matrix : 10
1 0 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0
0 0 0 1 0 0 0 0 0 0
0 0 0 0 1 0 0 0 0 0
0 0 0 0 0 1 0 0 0 0
0 0 0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 0 1 0
0 0 0 0 0 0 0 0 0 1

Enter the size of the matrix : 2
1 0
0 1

Leave a Reply