# Why does cumtrapz return negative values?

17 views (last 30 days)
Bas Wagemaker on 30 Dec 2019
Answered: Stijn Haenen on 30 Dec 2019
Hi!
I am trying to calculate the area underneath a small piece of line using cumtrapz. The line has a positive slope and has positive x and y value. However, cumtrapz returns negative values for the area:
area = 0 -0.0145 -0.0290 -0.0435 -0.0580
I think it has something to do with the stepsize of the X-vector. How can I accurately calculate the area underneath the line?
Thanks!
Bas
% Example of data
X=[0.5056 0.5048 0.5040 0.5032 0.5024];
Y=[18.1277 18.1241 18.1205 18.1170 18.1134];
% Calculating the area under the data
area=cumtrapz(X,Y);
% Plotting data
figure
plot(X,Y)
grid on

Stijn Haenen on 30 Dec 2019
Your X and Y are from high value to low values, resulting in negative areas.
use fliplr() to mirror arrays X and Y.
X=[0.5056 0.5048 0.5040 0.5032 0.5024];
Y=[18.1277 18.1241 18.1205 18.1170 18.1134];
% Calculating the area under the data
X=fliplr(X);
Y=fliplr(Y);
area=cumtrapz(X,Y);
% Plotting data
figure
plot(X,Y)
grid on