MCPcopy Create free account
hub / github.com/numpy/numpy / diag_indices

Function diag_indices

numpy/lib/index_tricks.py:920–985  ·  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

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

Callers 2

test_diag_indicesFunction · 0.90
diag_indices_fromFunction · 0.85

Calls

no outgoing calls

Tested by 1

test_diag_indicesFunction · 0.72