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
How to create an identity matrix using Numpy?
An identity matrix is a square matrix where diagonal elements are 1 and all other elements are 0. NumPy provides the identity() function to create identity matrices efficiently.
Syntax
numpy.identity(n, dtype=None)
Parameters
n: Size of the identity matrix (n x n)
dtype: Data type of the matrix elements (optional, defaults to float)
Creating a Basic Identity Matrix
import numpy as np # Create a 3x3 identity matrix identity_matrix = np.identity(3) print(identity_matrix)
[[1. 0. 0.] [0. 1. 0.] [0. 0. 1.]]
Specifying Data Type
import numpy as np # Create a 4x4 identity matrix with integer type identity_matrix = np.identity(4, dtype=int) print(identity_matrix)
[[1 0 0 0] [0 1 0 0] [0 0 1 0] [0 0 0 1]]
Using Different Data Types
import numpy as np
# Complex number identity matrix
complex_identity = np.identity(2, dtype=complex)
print("Complex identity matrix:")
print(complex_identity)
# Boolean identity matrix
bool_identity = np.identity(3, dtype=bool)
print("\nBoolean identity matrix:")
print(bool_identity)
Complex identity matrix: [[1.+0.j 0.+0.j] [0.+0.j 1.+0.j]] Boolean identity matrix: [[ True False False] [False True False] [False False True]]
Alternative: Using eye() Function
import numpy as np
# Using np.eye() for identity matrix
eye_matrix = np.eye(3, dtype=int)
print("Using np.eye():")
print(eye_matrix)
# np.eye() can also create rectangular matrices
rectangular = np.eye(3, 4, dtype=int)
print("\nRectangular matrix with np.eye():")
print(rectangular)
Using np.eye(): [[1 0 0] [0 1 0] [0 0 1]] Rectangular matrix with np.eye(): [[1 0 0 0] [0 1 0 0] [0 0 1 0]]
Comparison
| Function | Purpose | Shape |
|---|---|---|
np.identity(n) |
Square identity matrix | n x n only |
np.eye(n) |
Identity matrix (more flexible) | n x n or n x m |
Conclusion
Use np.identity() to create square identity matrices with specified data types. For more flexibility, including rectangular matrices, use np.eye() instead.
Advertisements
