NumPy Tutorial NumPy Statistics NumPy References

NumPy - matlib.eye() function

The NumPy matlib.eye() function returns a matrix with ones on the diagonal and zeros elsewhere.


numpy.matlib.eye(n, M=None, k=0, dtype='float', order='C')


n Required. Specify number of rows in the matrix.
M Optional. Specify number of columns in the matrix. Default is n.
k Optional. Specify index of the diagonal. 0 refers to the main diagonal, a positive value refers to an upper diagonal, and a negative value to a lower diagonal.
dtype Optional. Specify the desired data-type for the matrix. Default: float
order Optional. Specify whether to store the result. Two possible values are: C (C-style) and F (Fortran-style). Default: 'C'

Return Value

Returns a matrix with ones on the diagonal and zeros elsewhere.


In the example below, matlib.eye() function is used to create matrix using different available parameters.

import numpy as np
import numpy.matlib

#using default parameters
mat1 = np.matlib.eye(n=3)
print("mat1 is:\n", mat1)

#using positive k
mat2 = np.matlib.eye(n=3, M=4, k=1)
print("\nmat2 is:\n", mat2)

#using negative k with int data type
mat3 = np.matlib.eye(n=3, M=4, k=-1, dtype=int)
print("\nmat3 is:\n", mat3)

The output of the above code will be:

mat1 is:
 [[1. 0. 0.]
  [0. 1. 0.]
  [0. 0. 1.]]

mat2 is:
 [[0. 1. 0. 0.]
  [0. 0. 1. 0.]
  [0. 0. 0. 1.]]

mat3 is:
 [[0 0 0 0]
  [1 0 0 0]
  [0 1 0 0]]

❮ NumPy - Functions