# how to calculate the area under a curve?

2,106 views (last 30 days)
Davide Cerra on 9 Jul 2019
Commented: Rachel Natalie on 22 Apr 2022
x=[0:100];
y=30-60*cos(2*pi/100*x);
plot (y);
Hello! how con i calculate the area under the curve above? i would also like to calculate portions of that area.
thanks
Jan on 9 Jul 2019
Edited: Jan on 9 Jul 2019
I assume that #£ is a typo.
By the way, this is not twitter. No # before the tags. Thanks.

Jan on 9 Jul 2019
Edited: Jan on 9 Jul 2019
The area between a curve and the X axis is determined by the integral. So use trapz:
x = 0:100; % Square brackets waste time here only
y = 30 - 60 * cos(2 * pi / 100 * x);
A = trapz(x, y)
You can obtain the integral by hand also here:
30 * (x - 100*sin(pi * x / 50) / pi) + const.
Now insert the limits 0 and 100 to get 3000 as solution.

Star Strider on 9 Jul 2019
I would also like to calculate portions of that area.
Use cumtrapz, and then subtract the values of the limits:
x=[0:100];
y=30-60*cos(2*pi/100*x);
Int = cumtrapz(x,y);
Intv = @(a,b) max(Int(x<=b)) - min(Int(x>=a));
SegmentArea = Intv(25, 75)
SegmentArea =
3409.2309572264
Checking:
SegmentArea = integral(@(x)30-60*cos(2*pi/100*x), 25, 75)
SegmentArea =
3409.85931710274
Abolfazl Jalali Shahrood on 31 May 2020
Thanks for your instructions, what if we ignore max& min in the following function?
Intv = @(a,b) max(Int(x<=b)) - min(Int(x>=a));

GIULIA CISOTTO on 3 Nov 2020
If you would like to compute the integral of a function y(x) you can use:
Area = trapz(x,y);
or:
Int = cumtrapz(x,y);
However, if you are interested in computing the area under the curve (AUC), that is the sum of the portions of (x,y) plane in between the curve and the x-axis, you should preliminarily take the absolute value of y(x). That is, you should use the following code:
myInt = cumtrapz(x,abs(y));
myIntv = @(a,b) max(myInt(x<=b)) - min(myInt(x>=a));
AUC = myIntv(x(1), x(end));
Check it out the difference in the two computations in Figure 1 ('Your example') and Figure 2 ("1 cos period").
Figure 2 represents the toy example to check the correctness of your calculations. As we know, the integral of cos in one period (or its multiples) should be 0. Moreover, looking at the same Figure 1, we can do a double-check and roughtly compute the expected AUC between 33-th and 67-th sample as: 0.5*(67-33) + (67-33)*0.5/2 = 24 (the actual value being slightly larger).
Here are the results from the two different computations:
myInt(33,67) = 27.8845
Int(33,67) = 31.8205
##### 2 CommentsShowHide 1 older comment
Rachel Natalie on 22 Apr 2022
How did you plot the graph?