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