diff options
author | Matti Picus <matti.picus@gmail.com> | 2021-01-25 17:01:18 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-01-25 17:01:18 +0200 |
commit | d9dee6a6b95c3fea8747e591ef1f44f36445f70c (patch) | |
tree | 4093e79560d46ef65d551e483af2e63b75acdb12 /numpy/lib/twodim_base.py | |
parent | 6a9db2e5941bd0b7552103409141d7b5ee9f0d58 (diff) | |
parent | 2951e733d9ffa03276d6859721b57209234bea12 (diff) | |
download | numpy-d9dee6a6b95c3fea8747e591ef1f44f36445f70c.tar.gz |
Merge pull request #18176 from Illviljan/Illviljan-faster_tril_indices
ENH: Improve performance of tril_indices and triu_indices
Diffstat (limited to 'numpy/lib/twodim_base.py')
-rw-r--r-- | numpy/lib/twodim_base.py | 13 |
1 files changed, 10 insertions, 3 deletions
diff --git a/numpy/lib/twodim_base.py b/numpy/lib/twodim_base.py index 2b4cbdfbb..960797b68 100644 --- a/numpy/lib/twodim_base.py +++ b/numpy/lib/twodim_base.py @@ -6,11 +6,12 @@ import functools from numpy.core.numeric import ( asanyarray, arange, zeros, greater_equal, multiply, ones, asarray, where, int8, int16, int32, int64, empty, promote_types, diagonal, - nonzero + nonzero, indices ) from numpy.core.overrides import set_array_function_like_doc, set_module from numpy.core import overrides from numpy.core import iinfo +from numpy.lib.stride_tricks import broadcast_to __all__ = [ @@ -894,7 +895,10 @@ def tril_indices(n, k=0, m=None): [-10, -10, -10, -10]]) """ - return nonzero(tri(n, m, k=k, dtype=bool)) + tri_ = tri(n, m, k=k, dtype=bool) + + return tuple(broadcast_to(inds, tri_.shape)[tri_] + for inds in indices(tri_.shape, sparse=True)) def _trilu_indices_form_dispatcher(arr, k=None): @@ -1010,7 +1014,10 @@ def triu_indices(n, k=0, m=None): [ 12, 13, 14, -1]]) """ - return nonzero(~tri(n, m, k=k-1, dtype=bool)) + tri_ = ~tri(n, m, k=k - 1, dtype=bool) + + return tuple(broadcast_to(inds, tri_.shape)[tri_] + for inds in indices(tri_.shape, sparse=True)) @array_function_dispatch(_trilu_indices_form_dispatcher) |