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.]])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.