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

Issue

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

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

Answered By – mozway

Answer Checked By – David Goodson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *