NumPy: Create a 2-D array whose diagonal equals
NumPy: Array Object Exercise-43 with Solution
2D Array with Custom Diagonal Values
Write a NumPy program to create a 2-D array whose diagonal equals [4, 5, 6, 8] and 0's elsewhere.
Pictorial Presentation:
Sample Solution:
Python Code:
# Importing the NumPy library with an alias 'np'
import numpy as np
# Creating a 2-D array with the specified diagonal elements and zeros elsewhere
x = np.diagflat([4, 5, 6, 8])
# Printing the resulting 2-D array
print(x)
Sample Output:
[[4 0 0 0] [0 5 0 0] [0 0 6 0] [0 0 0 8]]
Explanation:
This code demonstrates how to create a diagonal matrix using the np.diagflat() function in NumPy.
x = np.diagflat([4, 5, 6, 8]): The current line creates a diagonal matrix ‘x’ using the np.diagflat() function. The function takes one argument, which is a list or array-like object containing the values to be placed on the diagonal of the resulting matrix.
print(x): The current line prints the diagonal matrix ‘x’.
Python-Numpy Code Editor:
Previous: Write a NumPy program to create a 3-D array with ones on the diagonal and zeros elsewhere.
Next: Write a NumPy program to create a 1-D array going from 0 to 50 and an array from 10 to 50.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
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://www.w3resource.com/python-exercises/numpy/python-numpy-exercise-43.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics