How to Create an Eye Matrix in NumPy: Simple Guide
Use
numpy.eye(n, M=None, k=0, dtype=float) to create a 2D array with ones on the diagonal and zeros elsewhere. Here, n is the number of rows, M is the number of columns (optional), and k shifts the diagonal. This function returns an identity-like matrix called an eye matrix.Syntax
The numpy.eye function creates a 2D array with ones on a specified diagonal and zeros elsewhere.
- n: Number of rows in the output matrix.
- M (optional): Number of columns. If not given, it defaults to
n. - k (optional): Index of the diagonal.
0is the main diagonal, positive values are above, negative below. - dtype (optional): Data type of the output array, default is
float.
python
numpy.eye(n, M=None, k=0, dtype=float)
Example
This example creates a 4x4 eye matrix with ones on the main diagonal and zeros elsewhere.
python
import numpy as np # Create a 4x4 eye matrix eye_matrix = np.eye(4) print(eye_matrix)
Output
[[1. 0. 0. 0.]
[0. 1. 0. 0.]
[0. 0. 1. 0.]
[0. 0. 0. 1.]]
Common Pitfalls
Common mistakes when using numpy.eye include:
- Not specifying
Mwhen you want a non-square matrix, which defaults to a square matrix. - Misunderstanding the
kparameter, which shifts the diagonal. Positivekmoves the diagonal up, negative moves it down. - Forgetting to set
dtypeif you need integers instead of floats.
python
import numpy as np # Wrong: expecting a 3x4 matrix but only passing n=3 wrong_eye = np.eye(3) print(wrong_eye) # Right: specify M=4 for 3 rows and 4 columns right_eye = np.eye(3, 4) print(right_eye) # Using k to shift diagonal up by 1 shifted_eye = np.eye(4, k=1) print(shifted_eye) # Using dtype=int for integer matrix int_eye = np.eye(3, dtype=int) print(int_eye)
Output
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
[[1. 0. 0. 0.]
[0. 1. 0. 0.]
[0. 0. 1. 0.]]
[[0. 1. 0. 0.]
[0. 0. 1. 0.]
[0. 0. 0. 1.]
[0. 0. 0. 0.]]
[[1 0 0]
[0 1 0]
[0 0 1]]
Quick Reference
| Parameter | Description | Default |
|---|---|---|
| n | Number of rows | Required |
| M | Number of columns | n (square matrix) |
| k | Diagonal offset (0=main, +up, -down) | 0 |
| dtype | Data type of output array | float |
Key Takeaways
Use numpy.eye(n) to create an n x n identity matrix with ones on the main diagonal.
Specify M to create a non-square eye matrix with different columns.
Use k to shift the diagonal up or down from the main diagonal.
Set dtype to control the data type, like int or float.
Remember numpy.eye returns a 2D array with ones on the specified diagonal and zeros elsewhere.