I have a numpy 2d array:
import numpy as np
A=np.array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]])
print (A)
I would like to replace the diagonal elements with a = np.array([0,2,15,20]). That is the desired output should be:
A=[[0, 2, 3, 4],
[5, 2, 7, 8],
[9, 10, 15, 12],
[13, 14, 15, 20]]
I tried with the following code:
import numpy as np
A=np.array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]])
a = np.array([0,2,15,20])
print(np.fill_diagonal(A, a))
But it resulted in None
np.fill_diagonalfunction modifies the input array in-place, it does not return a value. Tryprint(A)afterwards to see result.