Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a function in numpy to replace lower and upper diagonal values of a numpy array?

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

like image 973
user1419224 Avatar asked May 26 '12 16:05

user1419224


1 Answers

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.]])
like image 145
Fred Foo Avatar answered Sep 20 '22 01:09

Fred Foo