You can always use slicing to assign a value or array to diagonals.
Passing a list of row indexes and a list of column indices allows you to directly and directly access locations (and efficiently). For instance:
>>> z = np.zeros((5,5)) >>> z[np.arange(5), np.arange(5)] = 1
changes the array of zeros z to:
array([[ 1., 2., 0., 0., 0.], [ 11., 1., 2., 0., 0.], [ 0., 12., 1., 2., 0.], [ 0., 0., 13., 1., 2.], [ 0., 0., 0., 14., 1.]])
In the general case, for an array kxk called z , you can set the upper diagonal i th with
z[np.arange(ki), np.arange(ki) + i]
and lower lower diagonal i with
z[np.arange(ki) + i, np.arange(ki)]
Note. If you want to avoid calling np.arange several times, you can simply write ix = np.arange(k) once, and then cut this range as needed:
np.arange(ki) == ix[:-i]