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!
Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.