We can create numpy identity matrix with numpy.identity() function. We can parameterize n (number of rows) and data type as parameter. Actually, identity matrix is a square Matrix with all element as zero except element at principal diagonal of the matrix. This principal diagonal element will be one.
1. Create NumPy identity matrix ( Implementation)-
It is a single line code. All we need to call it with parameters. It will return the identity numpy array.
Step 1: Import Numpy-
We need to import the numpy module in the first step. As we can only use any function of any module after importing the module.
import numpy as np
Step 2: identity matrix creation –
Here we will call the numpy.identity() with the number of rows as a parameter.It will create the Identity Matrix of that shape.
2. Complete code with output –
Here is the complete code. Let’s run and see it.
import numpy as np np.identity(5)
Here the created matrix is of 5*5 shape. If we change the row number to four, It will be 4*4 of shape.
3. Data Type in Identity Matrix-
We can create Identity Matrix with different data types like int, float, etc. Only we need to provide the data type in the identity() function. Here is the way to achieve it.
import numpy as np np.identity(5, dtype=float)
We can provide also str as the data type. Here is an example for this.
import numpy as np np.identity(5, dtype=str)
We can see all the elements are one at the diagonal. other elements are none.
Identity Matrix is a squire matrix with all elements is one at its main diagonal. Apart from this diagonal, every element will be zero. We have implemented this with numpy module in python. I hope this implementation must have solved this for you, please do not forget to comment your views on this topic.
Data Science Learner Team
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.