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

Efficient negation of subdiagonal values of a 2d numpy array

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

>Solution :

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

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 !

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