dpnp.diag

dpnp.diag(v, /, k=0, *, device=None, usm_type=None, sycl_queue=None)[source]

Extract a diagonal or construct a diagonal array.

For full documentation refer to numpy.diag.

Parameters:
  • v (array_like) -- Input data, in any form that can be converted to an array. This includes scalars, lists, lists of tuples, tuples, tuples of tuples, tuples of lists, and ndarrays. If v is a 2-D array, return a copy of its k-th diagonal. If v is a 1-D array, return a 2-D array with v on the k-th diagonal.

  • k (int, optional) -- Diagonal in question. The default is 0. Use k > 0 for diagonals above the main diagonal, and k < 0 for diagonals below the main diagonal.

  • device ({None, string, SyclDevice, SyclQueue}, optional) -- An array API concept of device where the output array is created. The device can be None (the default), an OneAPI filter selector string, an instance of dpctl.SyclDevice corresponding to a non-partitioned SYCL device, an instance of dpctl.SyclQueue, or a Device object returned by dpnp.dpnp_array.dpnp_array.device property.

  • usm_type ({None, "device", "shared", "host"}, optional) -- The type of SYCL USM allocation for the output array. Default is None.

  • sycl_queue ({None, SyclQueue}, optional) -- A SYCL queue to use for output array allocation and copying.

Returns:

out -- The extracted diagonal or constructed diagonal array.

Return type:

dpnp.ndarray

See also

diagonal

Return specified diagonals.

diagflat

Create a 2-D array with the flattened input as a diagonal.

trace

Return sum along diagonals.

triu

Return upper triangle of an array.

tril

Return lower triangle of an array.

Examples

>>> import dpnp as np
>>> x0 = np.arange(9).reshape((3, 3))
>>> x0
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
>>> np.diag(x0)
array([0, 4, 8])
>>> np.diag(x0, k=1)
array([1, 5])
>>> np.diag(x0, k=-1)
array([3, 7])
>>> np.diag(np.diag(x0))
array([[0, 0, 0],
       [0, 4, 0],
       [0, 0, 8]])

Creating an array on a different device or with a specified usm_type

>>> x = np.diag(x0) # default case
>>> x, x.device, x.usm_type
(array([0, 4, 8]), Device(level_zero:gpu:0), 'device')
>>> y = np.diag(x0, device="cpu")
>>> y, y.device, y.usm_type
(array([0, 4, 8]), Device(opencl:cpu:0), 'device')
>>> z = np.diag(x0, usm_type="host")
>>> z, z.device, z.usm_type
(array([0, 4, 8]), Device(level_zero:gpu:0), 'host')