bundles / numpy 2.4.3 / numpy / tril_indices
function
numpy:tril_indices
Signature
def tril_indices(n, k = 0, m = None)Summary
Return the indices for the lower-triangle of an (n, m) array.
Parameters
n: intThe row dimension of the arrays for which the returned indices will be valid.
k: int, optionalDiagonal offset (see tril for details).
m: int, optionalThe column dimension of the arrays for which the returned arrays will be valid. By default
mis taken equal ton.
Returns
inds: tuple of arraysThe row and column indices, respectively. The row indices are sorted in non-decreasing order, and the corresponding column indices are strictly increasing for each row.
Examples
import numpy as np
✓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 corresponding column 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) a✓
array([[ 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, 8, 9, 10, 12, 13, 14, 15])And for assigning values:
a[il1] = -1 a✓
array([[-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 a✓
array([[-10, -10, -10, 3],
[-10, -10, -10, -10],
[-10, -10, -10, -10],
[-10, -10, -10, -10]])
See also
- mask_indices
generic function accepting an arbitrary mask function.
- tril
- triu
- triu_indices
similar function, for upper-triangular.
Aliases
numpy.tril_indices