How to create numpy identity matrix in Python

How to create numpy identity matrix in Python ?

GET FREE AMZAON AUDIOBOOKS

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.

np.identity(5)

 

2. Complete code with output –

Here is the complete code. Let’s run and see it.

import numpy as np
np.identity(5)
numpy identity matrix
numpy identity matrix

 

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)
numpy identity float type
numpy identity float type

 

We can provide also str as the data type. Here is an example for this.

import numpy as np
np.identity(5, dtype=str)
numpy identity str type
numpy identity str type

We can see all the elements are one at the diagonal.  other elements are none.

numpy matrix
numpy matrix

Conclusion –

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.

 

Thanks
Data Science Learner Team

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

 
Thank you For sharing.We appreciate your support. Don't Forget to LIKE and FOLLOW our SITE to keep UPDATED with Data Science Learner