np.eye()
np.eye() builds an identity matrix: ones along the diagonal and zeros everywhere else.
In this page:
Syntax
np.eye(n)
np.eye(rows, cols, k=offset)
np.eye()
The identity matrix is the matrix equivalent of the number 1: multiplying by it changes nothing. np.eye(n) gives an n by n identity; np.identity(n) is similar. The k argument shifts the diagonal up or down.
Note:
np.diag can build a matrix from your own diagonal values.
Example: np.eye()
import numpy as np
print(np.eye(3))
print(np.eye(3, k=1, dtype=int))
# Output:
# [[1. 0. 0.]
# [0. 1. 0.]
# [0. 0. 1.]]
# [[0 1 0]
# [0 0 1]
# [0 0 0]]
Related Topics
Common Mistakes
- Passing a shape tuple instead of an integer size
- Forgetting the result is float by default
- Confusing eye with ones
Chapter Summary
- eye(n) makes an identity matrix
- k shifts the diagonal
- Default dtype is float
- Multiplying by identity leaves a matrix unchanged
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: