w3resource

NumPy: Create a 3-D array with ones on the diagonal and zeros elsewhere

NumPy: Array Object Exercise-42 with Solution

Write a NumPy program to create a 3-D array with ones on a diagonal and zeros elsewhere.

Pictorial Presentation:

Python NumPy: Create a 3-D array with ones on the diagonal and zeros elsewhere

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:

Previous: Write a NumPy program to create an array of 10's with the same shape and type of an given array.
Next: Write a NumPy program to create a 2-D array whose diagonal equals [4, 5, 6, 8] and 0's elsewhere.

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/python-numpy-exercise-42.php