numpy: fill offset diagonal with different values
You can straightforwardly use np.diag
:
>>> d = np.sqrt(1 + np.arange(4))
>>> np.diag(d, 1)
array([[ 0. , 1. , 0. , 0. , 0. ],
[ 0. , 0. , 1.41421356, 0. , 0. ],
[ 0. , 0. , 0. , 1.73205081, 0. ],
[ 0. , 0. , 0. , 0. , 2. ],
[ 0. , 0. , 0. , 0. , 0. ]])
The second argument of np.diag
specifies the diagonal in question.
One way could be to create the array of zeros and then use indexing to select and fill the desired indices with the square-root values.
For example:
>>> z = np.zeros((5,5))
>>> rng = np.arange(4)
>>> z[rng, rng+1] = np.sqrt(rng+1)
>>> z
array([[ 0. , 1. , 0. , 0. , 0. ],
[ 0. , 0. , 1.41421356, 0. , 0. ],
[ 0. , 0. , 0. , 1.73205081, 0. ],
[ 0. , 0. , 0. , 0. , 2. ],
[ 0. , 0. , 0. , 0. , 0. ]])