To replace the main diagonal I have used np.fill_diagonal
:
matrix = np.zeros((4, 4), float)
main = np.array([2,2,2,2])
np.fill_diagonal(matrix, main)
but I also need to replace the upper and lower diagonals that are next to the main diagonal:
upper=np.array([1,1,1])
lower=np.array([7,7,7])
to get:
matrix=[[2 1 0 0]
[7 2 1 0]
[0 7 2 1]
[0 0 7 2]]
thank you
With some smart slicing, np.fill_diagonal
can do this too:
>>> np.fill_diagonal(matrix[:-1, 1:], upper)
>>> np.fill_diagonal(matrix[1:, :-1], lower)
>>> matrix
array([[ 2., 1., 0., 0.],
[ 7., 2., 1., 0.],
[ 0., 7., 2., 1.],
[ 0., 0., 7., 2.]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With