dpnp.fill_diagonal

dpnp.fill_diagonal(a, val, wrap=False)[source]

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.

For full documentation refer to numpy.fill_diagonal.

Parameters:
  • a ({dpnp.ndarray, usm_ndarray}) -- Array whose diagonal is to be filled in-place. It must be at least 2-D.

  • val ({dpnp.ndarray, usm_ndarray, scalar}) -- Value(s) to write on the diagonal. If val is scalar, the value is written along the diagonal. If array, the flattened val is written along the diagonal, repeating if necessary to fill all diagonal entries.

  • wrap (bool) -- It enables the diagonal "wrapped" after N columns. This affects only tall matrices. Default: False.

See also

dpnp.diag_indices

Return the indices to access the main diagonal of an array.

dpnp.diag_indices_from

Return the indices to access the main diagonal of an n-dimensional array.

Examples

>>> import dpnp as np
>>> a = np.zeros((3, 3), dtype=int)
>>> np.fill_diagonal(a, 5)
>>> a
array([[5, 0, 0],
       [0, 5, 0],
       [0, 0, 5]])

The same function can operate on a 4-D array:

>>> a = np.zeros((3, 3, 3, 3), dtype=int)
>>> np.fill_diagonal(a, 4)

We only show a few blocks for clarity:

>>> a[0, 0]
array([[4, 0, 0],
       [0, 0, 0],
       [0, 0, 0]])
>>> a[1, 1]
array([[0, 0, 0],
       [0, 4, 0],
       [0, 0, 0]])
>>> a[2, 2]
array([[0, 0, 0],
       [0, 0, 0],
       [0, 0, 4]])

The wrap option affects only tall matrices:

>>> # tall matrices no wrap
>>> a = np.zeros((5, 3), dtype=int)
>>> np.fill_diagonal(a, 4)
>>> a
array([[4, 0, 0],
       [0, 4, 0],
       [0, 0, 4],
       [0, 0, 0],
       [0, 0, 0]])
>>> # tall matrices wrap
>>> a = np.zeros((5, 3), dtype=int)
>>> np.fill_diagonal(a, 4, wrap=True)
>>> a
array([[4, 0, 0],
       [0, 4, 0],
       [0, 0, 4],
       [0, 0, 0],
       [4, 0, 0]])
>>> # wide matrices
>>> a = np.zeros((3, 5), dtype=int)
>>> np.fill_diagonal(a, 4, wrap=True)
>>> a
array([[4, 0, 0, 0, 0],
       [0, 4, 0, 0, 0],
       [0, 0, 4, 0, 0]])

The anti-diagonal can be filled by reversing the order of elements using either dpnp.flipud or dpnp.fliplr.

>>> a = np.zeros((3, 3), dtype=int)
>>> val = np.array([1, 2, 3])
>>> np.fill_diagonal(np.fliplr(a), val)  # Horizontal flip
>>> a
array([[0, 0, 1],
       [0, 2, 0],
       [3, 0, 0]])
>>> np.fill_diagonal(np.flipud(a), val)  # Vertical flip
>>> a
array([[0, 0, 3],
       [0, 2, 0],
       [1, 0, 0]])