NumPy: Create a 3-D array with ones on the diagonal and zeros elsewhere
3D Array with Diagonal Ones
Write a NumPy program to create a 3-D array with ones on a diagonal and zeros elsewhere.
Pictorial Presentation:
Sample Solution:
Python Code:
# Importing the NumPy library with an alias 'np'
import numpy as np
# Creating a 3x3 identity matrix using the eye method in NumPy
x = np.eye(3)
# Printing the created identity matrix
print(x)
Sample Output:
[[ 1. 0. 0.] [ 0. 1. 0.] [ 0. 0. 1.]]
Explanation:
The above code demonstrates how to create an identity matrix (a square matrix with ones on the diagonal and zeros elsewhere) using the np.eye() function in NumPy.
x = np.eye(3): np.eye(3This line creates a 3x3 identity matrix x using the np.eye() function. The function takes one argument, which is the number of rows (and columns, since it's a square matrix) in the resulting identity matrix.
print(x): This line prints the identity matrix x:
Python-Numpy Code Editor:
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