bs10reh
bs10reh

Reputation: 155

Setting increasing values in a numpy array around a defined diagonal

What is the best way to create a 2D list (or numpy array) in python, in which the diagonal is set to -1 and the remaining values are increasing from 0 by 1, for different values of n. For example, if n = 3 the array would look like:

[[-1,0,1]
 [2,-1,3]
 [4,5,-1]] 

or for n = 4:

[[-1,0,1,2]
 [3,-1,4,5]
 [6,7,-1,8]
 [9,10,11,-1]]

etc.

I know I can create an array with zeros and with the diagonal set to -1 with: a = numpy.zeros((n,n)) numpy.fill_diagonal(a,-1)

And so if n = 3 this would give:

[[-1,0,0]
 [0,-1,0]
 [0,0,-1]]

But how would I then set the 0's to be increasing numbers, as shown in the example above? Would I need to iterate through and set the values through a loop? Or is there a better way to approach this?

Thanks in advance.

Upvotes: 1

Views: 492

Answers (2)

B. M.
B. M.

Reputation: 18638

Here is an arithmetic way:

m=np.arange(n*n).reshape(n,n)*n//(n+1)
m.flat[::n+1]=-1

for n=5 :

[[-1  0  1  2  3]
 [ 4 -1  5  6  7]
 [ 8  9 -1 10 11]
 [12 13 14 -1 15]
 [16 17 18 19 -1]]

Upvotes: 0

Divakar
Divakar

Reputation: 221584

One approach -

def set_matrix(n):
    out = np.full((n,n),-1)
    off_diag_mask = ~np.eye(n,dtype=bool)
    out[off_diag_mask] = np.arange(n*n-n)
    return out

Sample runs -

In [23]: set_matrix(3)
Out[23]: 
array([[-1,  0,  1],
       [ 2, -1,  3],
       [ 4,  5, -1]])

In [24]: set_matrix(4)
Out[24]: 
array([[-1,  0,  1,  2],
       [ 3, -1,  4,  5],
       [ 6,  7, -1,  8],
       [ 9, 10, 11, -1]])

Upvotes: 1

Related Questions