v4k7or
v4k7or

Reputation: 33

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

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.

Upvotes: 3

Views: 701

Answers (2)

balu
balu

Reputation: 1143

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]]

Upvotes: 3

negstek
negstek

Reputation: 691

Maybe you should try with a double loop

Upvotes: 2

Related Questions