Home > Net >  Numpy get secondary diagonal with offset=1 and change the values
Numpy get secondary diagonal with offset=1 and change the values

Time:03-02

I have this 6x6 matrix filled with 0s. I got the secondary diagonal in sec_diag. The thing I am trying to do is to change the values of above the sec_diag inside the matrix with the odds numbers from 9-1 [9,7,5,3,1]

import numpy as np
x = np.zeros((6,6), int)
sec_diag = np.diagonal(np.fliplr(x), offset=1)

The result should look like this:

[[0,0,0,0,9,0],
 [0,0,0,7,0,0],
 [0,0,5,0,0,0],
 [0,3,0,0,0,0],
 [1,0,0,0,0,0],
 [0,0,0,0,0,0]]

EDIT: np.fill_diagonal isn't going to work.

CodePudding user response:

Maybe you should try with a double loop

CodePudding user response:

You should use roll

x = np.zeros((6,6),dtype=np.int32)
np.fill_diagonal(np.fliplr(x), [9,7,5,3,1,0])
xr = np.roll(x,-1,axis=1)
print(xr)

Output

[[0 0 0 0 9 0]
 [0 0 0 7 0 0]
 [0 0 5 0 0 0]
 [0 3 0 0 0 0]
 [1 0 0 0 0 0]
 [0 0 0 0 0 0]]
  • Related