NumPy matlib.identity() Function:
The matlib.identity() method of the NumPy module creates a square identity matrix of the specified size.
Syntax:
numpy.matlib.identity(n, dtype=None)
Parameters
n: This is required. The size of the resultant identity matrix is denoted by n.
dtype: This is optional. It denotes the output matrix data type. float is the default value.
Return Value:
This function returns a square identity matrix of the specified size.
NumPy matlib.identity() Function in Python
Example1
Approach:
- Import numpy module using the import keyword.
- Import matlib function of numpy module using the import keyword.
- Pass the size of the matrix(n) value as an argument to the matlib.identity() function of numpy module to create a square identity matrix of above-given size.
- Store it in a variable.
- Print the above obtained square identity matrix of a given size
- The Exit of the Program.
Below is the implementation:
# Import numpy module using the import keyword
import numpy as np
# Import matlib function of numpy module using the import keyword
import numpy.matlib
# Pass the size of the matrix(n) value as an argument to the matlib.identity() function
# of numpy module to create a square identity matrix of above given size.
# Store it in a variable.
gvn_matrx = np.matlib.identity(4)
# Print the above obtained square identity matrix of a given size
print("The above obtained square identity matrix of given size:\n", gvn_matrx)
Output:
The above obtained square identity matrix of given size: [[1. 0. 0. 0.] [0. 1. 0. 0.] [0. 0. 1. 0.] [0. 0. 0. 1.]]
Example2
Approach:
- Import numpy module using the import keyword.
- Import matlib function of numpy module using the import keyword.
- Pass the size of the matrix(n), datatype value as int as the arguments to the matlib.identity() function of numpy module to create a square identity matrix of above-given size with the integer values.
- Store it in a variable.
- Print the above obtained square identity matrix of a given size with integer values
- The Exit of the Program.
Below is the implementation:
# Import numpy module using the import keyword
import numpy as np
# Import matlib function of numpy module using the import keyword
import numpy.matlib
# Pass the size of the matrix(n), dtataype value as int as the arguments to the
# matlib.identity() function of numpy module to create a square
# identity matrix of above given size with the integer values.
# Store it in a variable.
gvn_matrx = np.matlib.identity(4, dtype=int)
# Print the above obtained square identity matrix of given size with integer values
print("The above obtained square identity matrix of given size with integer values:")
print(gvn_matrx)
Output:
The above obtained square identity matrix of given size with integer values: [[1 0 0 0] [0 1 0 0] [0 0 1 0] [0 0 0 1]]