MCPcopy Index your code
hub / github.com/numpy/numpy / diag_indices

Function diag_indices

numpy/lib/_index_tricks_impl.py:927–990  ·  view source on GitHub ↗

Return the indices to access the main diagonal of an array. This returns a tuple of indices that can be used to access the main diagonal of an array `a` with ``a.ndim >= 2`` dimensions and shape (n, n, ..., n). For ``a.ndim = 2`` this is the usual diagonal, for ``a.ndim > 2`` t

(n, ndim=2)

Source from the content-addressed store, hash-verified

925
926@set_module('numpy')
927def diag_indices(n, ndim=2):
928 """
929 Return the indices to access the main diagonal of an array.
930
931 This returns a tuple of indices that can be used to access the main
932 diagonal of an array `a` with ``a.ndim >= 2`` dimensions and shape
933 (n, n, ..., n). For ``a.ndim = 2`` this is the usual diagonal, for
934 ``a.ndim > 2`` this is the set of indices to access ``a[i, i, ..., i]``
935 for ``i = [0..n-1]``.
936
937 Parameters
938 ----------
939 n : int
940 The size, along each dimension, of the arrays for which the returned
941 indices can be used.
942
943 ndim : int, optional
944 The number of dimensions.
945
946 See Also
947 --------
948 diag_indices_from
949
950 Examples
951 --------
952 >>> import numpy as np
953
954 Create a set of indices to access the diagonal of a (4, 4) array:
955
956 >>> di = np.diag_indices(4)
957 >>> di
958 (array([0, 1, 2, 3]), array([0, 1, 2, 3]))
959 >>> a = np.arange(16).reshape(4, 4)
960 >>> a
961 array([[ 0, 1, 2, 3],
962 [ 4, 5, 6, 7],
963 [ 8, 9, 10, 11],
964 [12, 13, 14, 15]])
965 >>> a[di] = 100
966 >>> a
967 array([[100, 1, 2, 3],
968 [ 4, 100, 6, 7],
969 [ 8, 9, 100, 11],
970 [ 12, 13, 14, 100]])
971
972 Now, we create indices to manipulate a 3-D array:
973
974 >>> d3 = np.diag_indices(2, 3)
975 >>> d3
976 (array([0, 1]), array([0, 1]), array([0, 1]))
977
978 And use it to set the diagonal of an array of zeros to 1:
979
980 >>> a = np.zeros((2, 2, 2), dtype=np.int_)
981 >>> a[d3] = 1
982 >>> a
983 array([[[1, 0],
984 [0, 0]],

Callers 2

test_diag_indicesFunction · 0.90
diag_indices_fromFunction · 0.85

Calls

no outgoing calls

Tested by 1

test_diag_indicesFunction · 0.72

Used in the wild real call sites across dependent graphs

searching dependent graphs…