diagonal

sparse.diagonal(a, offset=0, axis1=0, axis2=1)[source]

Extract diagonal from a COO array. The equivalent of numpy.diagonal.

Parameters:
  • a (COO) – The array to perform the operation on.

  • offset (int, optional) – Offset of the diagonal from the main diagonal. Defaults to main diagonal (0).

  • axis1 (int, optional) – First axis from which the diagonals should be taken. Defaults to first axis (0).

  • axis2 (int, optional) – Second axis from which the diagonals should be taken. Defaults to second axis (1).

Examples

>>> import sparse
>>> x = sparse.as_coo(np.arange(9).reshape(3, 3))
>>> sparse.diagonal(x).todense()
array([0, 4, 8])
>>> sparse.diagonal(x, offset=1).todense()
array([1, 5])
>>> x = sparse.as_coo(np.arange(12).reshape((2, 3, 2)))
>>> x_diag = sparse.diagonal(x, axis1=0, axis2=2)
>>> x_diag.shape
(3, 2)
>>> x_diag.todense()
array([[ 0,  7],
       [ 2,  9],
       [ 4, 11]])
Returns:

out – The result of the operation.

Return type:

COO

Raises:

ValueError – If a.shape[axis1] != a.shape[axis2]

See also

numpy.diagonal

NumPy equivalent function