📜  Python numpy.matlib.eye()(1)

📅  最后修改于: 2023-12-03 14:46:01.208000             🧑  作者: Mango

Python numpy.matlib.eye()

The numpy.matlib.eye() function in Python is used to create a 2-D identity matrix or a 2-D array with ones on the diagonal and zeros elsewhere. It is a part of the numpy.matlib module.

Syntax:
numpy.matlib.eye(n, M=None, k=0, dtype=<class 'float'>, order='C')
Parameters:
  • n: (int) Number of rows in the output matrix.
  • M: (int, optional) Number of columns in the output matrix. If None, defaults to n (square matrix).
  • k: (int, optional) Index of the diagonal, with the main diagonal represented by 0. Default is 0.
  • dtype: (data-type, optional) The desired data-type for the array. Default is float.
  • order: (str, optional) Whether to store the multi-dimensional data in row-major (C-style) or column-major (Fortran-style) order. Default is 'C'.
Returns:
  • A 2-D array or a matrix with ones on the diagonal and zeros elsewhere.
Example:
import numpy as np

# Create a 2x2 identity matrix
matrix1 = np.matlib.eye(2)
print(matrix1)

Output:

[[1. 0.]
 [0. 1.]]

In the above example, numpy.matlib.eye(2) creates a 2x2 identity matrix with ones on the main diagonal and zeros elsewhere.

Additional Examples:
import numpy as np

# Create a 3x3 identity matrix
matrix2 = np.matlib.eye(3)
print(matrix2)

Output:

[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]
import numpy as np

# Create a 4x5 identity matrix
matrix3 = np.matlib.eye(4, 5)
print(matrix3)

Output:

[[1. 0. 0. 0. 0.]
 [0. 1. 0. 0. 0.]
 [0. 0. 1. 0. 0.]
 [0. 0. 0. 1. 0.]]
Conclusion:

The numpy.matlib.eye() function is a useful tool when you need to create identity matrices in Python. It simplifies the task of generating arrays or matrices with ones on the diagonal and zeros elsewhere.