Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python Program to Print an Identity Matrix
An identity matrix is a square matrix where the diagonal elements are 1 and all other elements are 0. In Python, you can create an identity matrix using nested loops or the NumPy library.
Using Nested Loops
The basic approach uses two nested loops to check if the row index equals the column index ?
n = 4
print("The value of n has been initialized to " + str(n))
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()
The value of n has been initialized to 4 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1
Using NumPy
NumPy provides a built-in function eye() to create identity matrices ?
import numpy as np
n = 4
identity_matrix = np.eye(n, dtype=int)
print("Identity matrix using NumPy:")
print(identity_matrix)
Identity matrix using NumPy: [[1 0 0 0] [0 1 0 0] [0 0 1 0] [0 0 0 1]]
How It Works
In the nested loop approach:
- The outer loop iterates through rows (i from 0 to n-1)
- The inner loop iterates through columns (j from 0 to n-1)
- When i equals j (diagonal position), print "1"
- When i does not equal j (off-diagonal position), print "0"
- After each row,
print()moves to the next line
Comparison
| Method | Advantages | Best For |
|---|---|---|
| Nested Loops | No external libraries, educational | Learning matrix concepts |
| NumPy eye() | Concise, optimized, returns array | Scientific computing |
Conclusion
Use nested loops to understand the concept of identity matrices. For practical applications, NumPy's eye() function is more efficient and returns a proper matrix object.
Advertisements
