Python NumPy Eye() Function Example
Python NumPy eye() is an inbuilt NumPy function that is used for returning a matrix i.e., a 2D array having 1’s at its diagonal and 0’s elsewhere w.r.t to a specific position i.e., kth value. It generally consists of five parameters mentioned below the syntax. It is defined under NumPy, which can be imported as import NumPy as np, and we can create multidimensional arrays and derive other mathematical statistics with the help of NumPy, which is a library in Python.
Python NumPy Eye()
Python numpy.eye() is an inbuilt method that returns the array of shape, R x C, where all items are equal to zero, except for the kth diagonal, whose values are equal to one.
numpy.eye(N, M=None, k=0, dtype=<class 'float'>, order='C')
- N: It represents a number of rows in a 2D array.
- M: It represents the number of columns. It an optional argument, and by default, it is equal to the value N i.e., several rows.
- k: This argument is used for representing the Diagonal. It is entirely optional.
By default, it is equal to 0. A positive value (k>0) refers to an upper diagonal, and a negative value(k<0) to a lower diagonal.
- dtype: It denotes the data type of returned array. It is entirely optional, and by default, it is a float.
- order: The order parameter can be either C_contiguous or F_contiguous.
The numpy.eye () method returns a 2D array of shape, N x M i.e., a matrix where all elements are equal to zero, except for the kth diagonal, whose values are equal to one.
Write a python program to show the working of the NumPy.eye() method.
import numpy as np # 2x2 matrix with 1's on main diagonal obj1 = np.eye(2, dtype=float) print("Matrix : \n", obj1) # matrix with Row=2 Column=3 and diagonal=1 obj2 = np.eye(2, 3, k=1) print("\nMatrix : \n", obj2) # matrix with Row=3 Column=3 and diagonal=-1 obj2 = np.eye(3, 3, k=1) print("\nMatrix : \n", obj2)
Matrix : [[1. 0.] [0. 1.]] Matrix : [[0. 1. 0.] [0. 0. 1.]] Matrix : [[0. 1. 0.] [0. 0. 1.] [0. 0. 0.]]
In 1st function number of rows was 3, and as column value was not declared, so by default, it became equal to rows, and a matrix of 3 X 3 was displayed having its main diagonal with value 1.
In 2nd function number of rows was 2, and the column was 3, so a matrix of 2 X 3 was displayed having its upper diagonal as 1.
In the 3rd function number of rows was 3, and the column was 3, so a matrix of 3 X 3 was displayed having its lower diagonal as 1.