numpy.tril_indices#

numpy.tril_indices(n,k=0,m=None)[source]#

Return the indices for the lower-triangle of an (n, m) array.

Parameters:
nint

The row dimension of the arrays for which the returnedindices will be valid.

kint, optional

Diagonal offset (seetril for details).

mint, optional

The column dimension of the arrays for which the returnedarrays will be valid.By defaultm is taken equal ton.

Returns:
indstuple of arrays

The row and column indices, respectively. The row indices are sortedin non-decreasing order, and the corresponding column indices arestrictly increasing for each row.

See also

triu_indices

similar function, for upper-triangular.

mask_indices

generic function accepting an arbitrary mask function.

tril,triu

Examples

>>>importnumpyasnp

Compute two different sets of indices to access 4x4 arrays, one for thelower triangular part starting at the main diagonal, and one starting twodiagonals further right:

>>>il1=np.tril_indices(4)>>>il1(array([0, 1, 1, 2, 2, 2, 3, 3, 3, 3]), array([0, 0, 1, 0, 1, 2, 0, 1, 2, 3]))

Note that row indices (first array) are non-decreasing, and the correspondingcolumn indices (second array) are strictly increasing for each row.Here is how they can be used with a sample array:

>>>a=np.arange(16).reshape(4,4)>>>aarray([[ 0,  1,  2,  3],       [ 4,  5,  6,  7],       [ 8,  9, 10, 11],       [12, 13, 14, 15]])

Both for indexing:

>>>a[il1]array([ 0,  4,  5, ..., 13, 14, 15])

And for assigning values:

>>>a[il1]=-1>>>aarray([[-1,  1,  2,  3],       [-1, -1,  6,  7],       [-1, -1, -1, 11],       [-1, -1, -1, -1]])

These cover almost the whole array (two diagonals right of the main one):

>>>il2=np.tril_indices(4,2)>>>a[il2]=-10>>>aarray([[-10, -10, -10,   3],       [-10, -10, -10, -10],       [-10, -10, -10, -10],       [-10, -10, -10, -10]])
On this page