Fill the main diagonal of the given array of any dimensionality. For an array `a` with ``a.ndim >= 2``, the diagonal is the list of locations with indices ``a[i, ..., i]`` all identical. This function modifies the input array in-place, it does not return a value. Parameters ---
(a, val, wrap=False)
| 784 | |
| 785 | @array_function_dispatch(_fill_diagonal_dispatcher) |
| 786 | def fill_diagonal(a, val, wrap=False): |
| 787 | """Fill the main diagonal of the given array of any dimensionality. |
| 788 | |
| 789 | For an array `a` with ``a.ndim >= 2``, the diagonal is the list of |
| 790 | locations with indices ``a[i, ..., i]`` all identical. This function |
| 791 | modifies the input array in-place, it does not return a value. |
| 792 | |
| 793 | Parameters |
| 794 | ---------- |
| 795 | a : array, at least 2-D. |
| 796 | Array whose diagonal is to be filled, it gets modified in-place. |
| 797 | |
| 798 | val : scalar or array_like |
| 799 | Value(s) to write on the diagonal. If `val` is scalar, the value is |
| 800 | written along the diagonal. If array-like, the flattened `val` is |
| 801 | written along the diagonal, repeating if necessary to fill all |
| 802 | diagonal entries. |
| 803 | |
| 804 | wrap : bool |
| 805 | For tall matrices in NumPy version up to 1.6.2, the |
| 806 | diagonal "wrapped" after N columns. You can have this behavior |
| 807 | with this option. This affects only tall matrices. |
| 808 | |
| 809 | See also |
| 810 | -------- |
| 811 | diag_indices, diag_indices_from |
| 812 | |
| 813 | Notes |
| 814 | ----- |
| 815 | .. versionadded:: 1.4.0 |
| 816 | |
| 817 | This functionality can be obtained via `diag_indices`, but internally |
| 818 | this version uses a much faster implementation that never constructs the |
| 819 | indices and uses simple slicing. |
| 820 | |
| 821 | Examples |
| 822 | -------- |
| 823 | >>> a = np.zeros((3, 3), int) |
| 824 | >>> np.fill_diagonal(a, 5) |
| 825 | >>> a |
| 826 | array([[5, 0, 0], |
| 827 | [0, 5, 0], |
| 828 | [0, 0, 5]]) |
| 829 | |
| 830 | The same function can operate on a 4-D array: |
| 831 | |
| 832 | >>> a = np.zeros((3, 3, 3, 3), int) |
| 833 | >>> np.fill_diagonal(a, 4) |
| 834 | |
| 835 | We only show a few blocks for clarity: |
| 836 | |
| 837 | >>> a[0, 0] |
| 838 | array([[4, 0, 0], |
| 839 | [0, 0, 0], |
| 840 | [0, 0, 0]]) |
| 841 | >>> a[1, 1] |
| 842 | array([[0, 0, 0], |
| 843 | [0, 4, 0], |