0

I have below numpy array

import numpy as np
np.identity(13)

Now I like to replace all off-diagonal elements with some other number, say 0.45.

Is there any direct method available to perform this?

Brian Smith
  • 1,200
  • 4
  • 16
  • Does this answer your question? [In matrix of 100 x 100 in python, filling the off diagonal elements](https://stackoverflow.com/questions/20651432/in-matrix-of-100-x-100-in-python-filling-the-off-diagonal-elements) – Renat Dec 06 '22 at 16:12

2 Answers2

2

You can use numpy.where

np.where(np.identity(13)==0, 0.45, 1)
SomeDude
  • 13,876
  • 5
  • 21
  • 44
1

What about the following?

import numpy as np
n = 13
val_offdiag = 0.45
val_diag = 1
a = np.full((n ,n), val_offdiag) - np.identity(n) * (val_offdiag - val_diag)
andthum
  • 87
  • 6