Skip to content

cumsum

cumsum(x: array, axis: int = 0) -> array

Cumulative sum of x along axis, with a leading zero: the output has one more element than x along axis (e.g. to turn counts into pointers/offsets).

Parameters:

Name Type Description Default
x array

The input array.

required
axis int

The axis along which to sum. Default: 0

0

Returns:

Type Description
array

An array whose size along axis is x.shape[axis] + 1.

Example:

cumsum(mx.array([2, 4, 1]))
# mx.array([0, 2, 6, 7])
Source code in mlx_graphs/utils/indexing.py
def cumsum(x: mx.array, axis: int = 0) -> mx.array:
    """
    Cumulative sum of ``x`` along ``axis``, with a leading zero: the output
    has one more element than ``x`` along ``axis`` (e.g. to turn counts into
    pointers/offsets).

    Args:
        x: The input array.
        axis: The axis along which to sum. Default: ``0``

    Returns:
        An array whose size along ``axis`` is ``x.shape[axis] + 1``.

    Example:

    .. code-block:: python

        cumsum(mx.array([2, 4, 1]))
        # mx.array([0, 2, 6, 7])
    """
    axis = axis + x.ndim if axis < 0 else axis
    zero_shape = list(x.shape)
    zero_shape[axis] = 1
    zeros = mx.zeros(zero_shape, dtype=x.dtype)
    return mx.concatenate([zeros, mx.cumsum(x, axis=axis)], axis=axis)

from mlx_graphs.utils import cumsum · mlx_graphs/utils/indexing.py