Matlab vs. Python Numpy cumsum
A common numerical operation is cumulative summing.
The cumsum() operation has the output array of the same shape as the input array, with each element as the sum of all the previous elements in that dimension.
Matlab
cumsum
and Python
numpy.cumsum
operate quite similarly.
When translating code between Matlab and Python, as always keep in mind Matlab’s one-based indexing vs. Python’s zero-based indexing.
That is, when using cumsum() over an axis, be sure to select the correct axis–Matlab cumsum(..., 1)
is equivalent to numpy.cumsum(..., axis=0)
.
These examples are equivalent. Suppose input:
x = [2, 3, 5, 8]
Matlab:
y = cumsum(x)
y =
2 5 10 18
Python:
y = numpy.cumsum(x)
>>> y
array([ 2, 5, 10, 18])