NumPy: Create a 3x3 identity matrix
NumPy: Basic Exercise-16 with Solution
Write a NumPy program to create a 3x3 identity matrix.
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.
Pictorial Presentation:
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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics