w3resource logo
Python Exercises

Python NumPy: Create a 2-D array whose diagonal equals

Python NumPy: Array Object Exercise-43 with Solution

Write a Python program to create a 2-D array whose diagonal equals [4, 5, 6, 8] and 0's elsewhere.

Sample Solution:-

Python Code:

import numpy as np
x =  np.diagflat([4, 5, 6, 8])
print(x)

Sample Output:

[[4 0 0 0]                                                             
 [0 5 0 0]                                                             
 [0 0 6 0]                                                             
 [0 0 0 8]]

Python Code Editor:

import numpy as np
x =  np.diagflat([4, 5, 6, 8])
print(x)

Improve this sample solution and post your code through Disqus