Python cumtrapz vs. Matlab

The 0-based indexing of Python / Numpy versus the 1-based indexing of Matlab is perhaps the most obvious difference when working between the languages. Other, more subtle defaults come into play and may not be immediately caught within functions except by manual checks.

In atmospheric science among other fields, cumulative integration implemented as cumulative trapezoidal numerical integration is a common function named “cumtrapz”. Distinctive behavior between Matlab cumtrapz and SciPy cumtrapz might not be immediately caught inside a function, although it’s obvious when manually checking. Specifically, SciPy cumtrapz needs the initial=0 argument to match Matlab. Let’s show this by example:

Example

In both languages, suppose

x = [-2.5, 5, 10]

Matlab (or GNU Octave) outputs:

y = cumtrapz(x)

[0, 1.25, 8.75]

Here comes the wrinkle–SciPy cumtrapz output one element less than the input by default:

scipy.integrate.cumtrapz(x)

[1.25, 8.75]

To match Matlab output from SciPy, add the initial=0 argument:

scipy.integrate.cumtrapz(x, initial=0)

[0, 1.25, 8.75]