numpy 1.22.4 Pypi GitHub Homepage
Other Docs
NotesParametersReturnsBackRef
mask_indices(n, mask_func, k=0)

Assume :None:None:`mask_func` is a function that, for a square array a of size (n, n) with a possible offset argument k, when called as mask_func(a, k) returns a new array with zeros in certain locations (functions like triu or tril do precisely this). Then this function returns the indices where the non-zero values would be located.

Notes

versionadded

Parameters

n : int

The returned indices will be valid to access arrays of shape (n, n).

mask_func : callable

A function whose call signature is similar to that of triu , tril . That is, mask_func(x, k) returns a boolean array, shaped like :None:None:`x`. k is an optional argument to the function.

k : scalar

An optional argument which is passed through to :None:None:`mask_func`. Functions like triu , tril take a second argument that is interpreted as an offset.

Returns

indices : tuple of arrays.

The n arrays of indices corresponding to the locations where mask_func(np.ones((n, n)), k) is True.

Return the indices to access (n, n) arrays, given a masking function.

See Also

tril
tril_indices
triu
triu_indices

Examples

These are the indices that would allow you to access the upper triangular part of any 3x3 array:

>>> iu = np.mask_indices(3, np.triu)

For example, if a is a 3x3 array:

>>> a = np.arange(9).reshape(3, 3)
... a array([[0, 1, 2], [3, 4, 5], [6, 7, 8]])
>>> a[iu]
array([0, 1, 2, 4, 5, 8])

An offset can be passed also to the masking function. This gets us the indices starting on the first diagonal right of the main one:

>>> iu1 = np.mask_indices(3, np.triu, 1)

with which we now extract only three elements:

>>> a[iu1]
array([1, 2, 5])
See :

Back References

The following pages refer to to this document either explicitly or contain code examples using this.

numpy.tril_indices numpy.triu_indices

Local connectivity graph

Hover to see nodes names; edges to Self not shown, Caped at 50 nodes.

Using a canvas is more power efficient and can get hundred of nodes ; but does not allow hyperlinks; , arrows or text (beyond on hover)

SVG is more flexible but power hungry; and does not scale well to 50 + nodes.

All aboves nodes referred to, (or are referred from) current nodes; Edges from Self to other have been omitted (or all nodes would be connected to the central node "self" which is not useful). Nodes are colored by the library they belong to, and scaled with the number of references pointing them


GitHub : /numpy/lib/twodim_base.py#823
type: <class 'function'>
Commit: