Return the indices to access the main diagonal of an n-dimensional array. See `diag_indices` for full details. Parameters ---------- arr : array, at least 2-D See Also -------- diag_indices Examples -------- >>> import numpy as np Create a 4 by 4
(arr)
| 996 | |
| 997 | @array_function_dispatch(_diag_indices_from) |
| 998 | def diag_indices_from(arr): |
| 999 | """ |
| 1000 | Return the indices to access the main diagonal of an n-dimensional array. |
| 1001 | |
| 1002 | See `diag_indices` for full details. |
| 1003 | |
| 1004 | Parameters |
| 1005 | ---------- |
| 1006 | arr : array, at least 2-D |
| 1007 | |
| 1008 | See Also |
| 1009 | -------- |
| 1010 | diag_indices |
| 1011 | |
| 1012 | Examples |
| 1013 | -------- |
| 1014 | >>> import numpy as np |
| 1015 | |
| 1016 | Create a 4 by 4 array. |
| 1017 | |
| 1018 | >>> a = np.arange(16).reshape(4, 4) |
| 1019 | >>> a |
| 1020 | array([[ 0, 1, 2, 3], |
| 1021 | [ 4, 5, 6, 7], |
| 1022 | [ 8, 9, 10, 11], |
| 1023 | [12, 13, 14, 15]]) |
| 1024 | |
| 1025 | Get the indices of the diagonal elements. |
| 1026 | |
| 1027 | >>> di = np.diag_indices_from(a) |
| 1028 | >>> di |
| 1029 | (array([0, 1, 2, 3]), array([0, 1, 2, 3])) |
| 1030 | |
| 1031 | >>> a[di] |
| 1032 | array([ 0, 5, 10, 15]) |
| 1033 | |
| 1034 | This is simply syntactic sugar for diag_indices. |
| 1035 | |
| 1036 | >>> np.diag_indices(a.shape[0]) |
| 1037 | (array([0, 1, 2, 3]), array([0, 1, 2, 3])) |
| 1038 | |
| 1039 | """ |
| 1040 | |
| 1041 | if not arr.ndim >= 2: |
| 1042 | raise ValueError("input array must be at least 2-d") |
| 1043 | # For more than d=2, the strided formula is only valid for arrays with |
| 1044 | # all dimensions equal, so we check first. |
| 1045 | if not np.all(diff(arr.shape) == 0): |
| 1046 | raise ValueError("All dimensions of input must be of equal length") |
| 1047 | |
| 1048 | return diag_indices(arr.shape[0], arr.ndim) |
searching dependent graphs…