Skip to content

diagonalize

Diagonalize a COO array. The new dimension is appended at the end.

Warning

sparse.diagonalize is not numpy compatible as there is no direct numpy equivalent. The API may change in the future.

Parameters:

Name Type Description Default
a Union[COO, ndarray, spmatrix]

The array to diagonalize.

required
axis int

The axis to diagonalize. Defaults to first axis (0).

0

Examples:

>>> import sparse
>>> x = sparse.as_coo(np.arange(1, 4))
>>> sparse.diagonalize(x).todense()
array([[1, 0, 0],
       [0, 2, 0],
       [0, 0, 3]])
>>> x = sparse.as_coo(np.arange(24).reshape((2, 3, 4)))
>>> x_diag = sparse.diagonalize(x, axis=1)
>>> x_diag.shape
(2, 3, 4, 3)

sparse.diagonalize is the inverse of sparse.diagonal

>>> a = sparse.random((3, 3, 3, 3, 3), density=0.3)
>>> a_diag = sparse.diagonalize(a, axis=2)
>>> (sparse.diagonal(a_diag, axis1=2, axis2=5) == a.transpose([0, 1, 3, 4, 2])).all()
<COO: shape=(), dtype=bool, nnz=0, fill_value=True>

Returns:

Name Type Description
out COO

The result of the operation.

See Also

numpy.diag : NumPy equivalent for 1D array

Source code in sparse/numba_backend/_coo/common.py
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
def diagonalize(a, axis=0):
    """
    Diagonalize a COO array. The new dimension is appended at the end.

    !!! warning

        [`sparse.diagonalize`][] is not [numpy][] compatible as there is no direct [numpy][] equivalent. The
        API may change in the future.

    Parameters
    ----------
    a : Union[COO, np.ndarray, scipy.sparse.spmatrix]
        The array to diagonalize.
    axis : int, optional
        The axis to diagonalize. Defaults to first axis (0).

    Examples
    --------
    >>> import sparse
    >>> x = sparse.as_coo(np.arange(1, 4))
    >>> sparse.diagonalize(x).todense()
    array([[1, 0, 0],
           [0, 2, 0],
           [0, 0, 3]])

    >>> x = sparse.as_coo(np.arange(24).reshape((2, 3, 4)))
    >>> x_diag = sparse.diagonalize(x, axis=1)
    >>> x_diag.shape
    (2, 3, 4, 3)

    [`sparse.diagonalize`][] is the inverse of [`sparse.diagonal`][]

    >>> a = sparse.random((3, 3, 3, 3, 3), density=0.3)
    >>> a_diag = sparse.diagonalize(a, axis=2)
    >>> (sparse.diagonal(a_diag, axis1=2, axis2=5) == a.transpose([0, 1, 3, 4, 2])).all()
    <COO: shape=(), dtype=bool, nnz=0, fill_value=True>

    Returns
    -------
    out: COO
        The result of the operation.

    See Also
    --------
    [`numpy.diag`][] : NumPy equivalent for 1D array
    """
    from .core import COO, as_coo

    a = as_coo(a)

    diag_shape = a.shape + (a.shape[axis],)
    diag_coords = np.vstack([a.coords, a.coords[axis]])

    return COO(diag_coords, a.data, diag_shape)