'A better way to create an NxN matrix, with specific diagonal and off diagonal elements with numpy

I need to make a NxN matrix and specify diagonal elements. This is what I tried so far, I was hoping to find a more elegant solution without loops.

N = 4
value_offdiag  = 2    

b = np.eye(N, N)
b[np.triu_indices(N, 1)] = value_offdiag
b[np.tril_indices(4, -1)] = value_offdiag

This works, but there's got to be a better way without using a loop. Just wanted to check (google search so far hasn't revealed much)



Solution 1:[1]

What about using numpy.fill_diagonal?

N = 4
value_offdiag = 2
b = np.ones((N,N))*value_offdiag
np.fill_diagonal(b,1)

print(b)

output:

[[1. 2. 2. 2.]
 [2. 1. 2. 2.]
 [2. 2. 1. 2.]
 [2. 2. 2. 1.]]

Solution 2:[2]

One-liner:

N = 4
value1 = 100
value2 = 234

a = np.eye(N)*value1 + abs(np.eye(N)-1)*value2

Output:

>>> a.astype(int)
array([[ 13, 240, 240, 240],
       [240,  13, 240, 240],
       [240, 240,  13, 240],
       [240, 240, 240,  13]])

Solution 3:[3]

You can use numpy.fill + numpy.fill_diagonal like below:

>>> a = np.full((4, 4), 2.0)
>>> np.fill_diagonal(a, 1)
>>> a
array([[1., 2., 2., 2.],
       [2., 1., 2., 2.],
       [2., 2., 1., 2.],
       [2., 2., 2., 1.]])

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mozway
Solution 2 richardec
Solution 3 I'mahdi