Efficient negation of subdiagonal values of a 2d numpy array

How would one efficiently negate the subdiagonal entries of a 2d numpy array?

>Solution :

You may use numpy.tril_indices to compute the indices of the subdiagonal entries, considering a diagonal offset of k = -1, and negate them with a mask, for instance:

import numpy as np

a = np.arange(16).reshape(4, 4)

>>> array([[ 0,  1,  2,  3],
           [ 4,  5,  6,  7],
           [ 8,  9, 10, 11],
           [12, 13, 14, 15]])

idx_low_tri = np.tril_indices(a.shape[0], k=-1)
a[idx_low_tri] = -a[idx_low_tri]

>>> array([[  0,   1,   2,   3],
           [ -4,   5,   6,   7],
           [ -8,  -9,  10,  11],
           [-12, -13, -14,  15]])

Hope this helps !

Leave a Reply