Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading