w3resource

NumPy: Create a 3x3 identity matrix

NumPy: Basic Exercise-16 with Solution

Write a NumPy program to create a 3x3 identity matrix.

This NumPy program generates a 3x3 identity matrix, which is a square matrix with ones on the main diagonal and zeros elsewhere. By using NumPy's built-in functions, it efficiently constructs this matrix. This program exemplifies how to create standard mathematical matrices in a straightforward manner using NumPy.

Sample Solution :

Python Code :

# Importing the NumPy library with an alias 'np'
import numpy as np

# Creating a 3x3 identity matrix using np.identity()
array_2D = np.identity(3)

# Printing a message indicating a 3x3 matrix
print('3x3 matrix:')

# Printing the 3x3 identity matrix
print(array_2D) 

Sample Output:

3x3 matrix:
[[ 1.  0.  0.]
 [ 0.  1.  0.]
 [ 0.  0.  1.]]                         

Explanation:

In the above code np.identity() function creates a 2D identity matrix with a size of 3x3. An identity matrix is a square matrix with ones on the diagonal and zeros elsewhere.

Visual Presentation:

NumPy: Create a 3x3 identity matrix.

Python-Numpy Code Editor:

Previous: NumPy program to create an array of all the even integers from 30 to 70.
Next: NumPy program to generate a random number between 0 and 1.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/numpy/basic/numpy-basic-exercise-16.php