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()
np.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
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
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()
    np.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)