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:
This program generates and prints an identity matrix of size 3x3. Thus we obtain:
You can change the size of your identity matrix easily:
with corresponding output:
Your matrix need not be a square matrix, eg;
This creates a 6x3 matrix with 1s along the diagonal (note that the diagonal has only 3 elements):
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:
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:
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.

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

Copyright @ Kodeclik 2023. All rights reserved.