Kodeclik Blog
Python numpy.eye()
The numpy.eye() function creates a 2-dimensional identity matrix with a specified number of rows and columns, or a square matrix with ones on the diagonal and zeros elsewhere. In this post, we will explore the various ways in which the numpy.eye() function can be used in Python.
Here is the simplest usage of the numpy.eye() function:
import numpy as np
print(np.eye(3))
This program generates and prints an identity matrix of size 3x3. Thus we obtain:
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
You can change the size of your identity matrix easily:
import numpy as np
print(np.eye(5))
with corresponding output:
[[1. 0. 0. 0. 0.]
[0. 1. 0. 0. 0.]
[0. 0. 1. 0. 0.]
[0. 0. 0. 1. 0.]
[0. 0. 0. 0. 1.]]
Your matrix need not be a square matrix, eg;
import numpy as np
print(np.eye(6,3))
This creates a 6x3 matrix with 1s along the diagonal (note that the diagonal has only 3 elements):
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]
You can also use the same numpy.eye() function to place 1s at an offset to the diagonal. For this purpose you use the “k” parameter, eg:
import numpy as np
# 1s along main diagonal
print(np.eye(3,k=0))
# 1s above the diagonal, one step
print(np.eye(3,k=1))
# 1s below the diagonal, one step
print(np.eye(3,k=-1))
Note that k=0 returns the same identity matrix as before. Positive values of k place the 1s to the right and above the main diagonal. Likewise, negative values of k places the 1s below and to the left of the main diagonal. The output is thus:
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
[[0. 1. 0.]
[0. 0. 1.]
[0. 0. 0.]]
[[0. 0. 0.]
[1. 0. 0.]
[0. 1. 0.]]
Thus, the numpy.eye() function is a powerful tool for creating identity matrices of various sizes and diagonal positions. It is simple to use and has several useful parameters that allow for customization.
If you liked learning about numpy.eye() learn about the numpy.diag() function!
Interested in more things Python? Checkout our post on Python queues. Also see our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Want to learn Python with us? Sign up for 1:1 or small group classes.