cumtrapz() vs. trapz() in matlab

trapz() is a function in MATLAB used to perform numerical integration of one-dimensional arrays. It calculates the integral of y with respect to x using the trapezoidal method, where y is a vector and x are the corresponding x-axis values. Its output is a scalar value.

cumtrapz() is also a function in MATLAB used to perform numerical integration on one-dimensional arrays. However, unlike the trapz() function, cumtrapz() returns the cumulative integral of y with respect to x using the trapezoidal method. Its output is an array having the same size as y.

Here is an example code showing how to use trapz() and cumtrapz() on a simple set of arrays:

main.m
%defining arrays
x = 0:0.1:2*pi;
y = sin(x);

%integrating using trapz
integral_trapz = trapz(x, y);

%integrating using cumtrapz
integral_cumtrapz = cumtrapz(x, y);

%plotting both curves
plot(x, y, 'r');
hold on;
plot(x, integral_cumtrapz, 'b');
248 chars
15 lines

In the example code, integral_trapz contains the area under the curve of the y array with respect to the x array (using the trapezoidal method), while integral_cumtrapz contains an array of the cumulative integral of y with respect to x.

gistlibby LogSnag