Numpy Tutorial
Creating NumPy Array
NumPy Array Manipulation
Matrix in NumPy
Operations on NumPy Array
Reshaping NumPy Array
Indexing NumPy Array
Arithmetic operations on NumPy Array
Linear Algebra in NumPy Array
NumPy and Random Data
Sorting and Searching in NumPy Array
Universal Functions
Working With Images
Projects and Applications with NumPy
The numpy.identity()
function is a quick and straightforward tool for generating identity matrices. This function complements numpy.eye()
, but it's specifically for creating square identity matrices.
An identity matrix is a square matrix in which all the elements of the principal (main) diagonal are ones and all other elements are zeros.
Start by importing the necessary library:
import numpy as np
numpy.identity()
:To generate a 3x3 identity matrix:
I = np.identity(3) print(I)
Output:
[[1. 0. 0.] [0. 1. 0.] [0. 0. 1.]]
As you can see, it's very direct. You just specify the size of the matrix (number of rows or columns since it's square), and the function does the rest.
You can also determine the data type of the matrix elements using the dtype
parameter:
I_int = np.identity(3, dtype=int) print(I_int)
Output:
[[1 0 0] [0 1 0] [0 0 1]]
numpy.eye()
and numpy.identity()
:While both functions can create identity matrices, there are some differences:
Flexibility: numpy.eye()
is more versatile. It can create non-square matrices and matrices with ones on off-diagonals, while numpy.identity()
strictly creates square identity matrices.
Simplicity: numpy.identity()
is simpler to use when you specifically need a square identity matrix since it requires fewer arguments.
An identity matrix serves as the "neutral element" in matrix multiplication, analogous to multiplying numbers by 1:
A = np.array([[5, 3], [8, 7]]) result = A @ np.identity(2) print(result)
Output:
[[5. 3.] [8. 7.]]
The product is the matrix A
itself, demonstrating the "neutral" property of the identity matrix.
The numpy.identity()
function provides a quick and concise way to generate square identity matrices in Python. Given the fundamental nature of identity matrices in linear algebra and numerical computations, having such a function at your disposal is immensely useful. Whether you're working with matrix equations, initializing matrices, or performing other matrix operations, the identity matrix is an indispensable tool.