Irregular shape area calculation using "integral"

14 views (last 30 days)
I have a a graph that is irregular shape with many data points. However, for the sake of simplicity I am gona ask here simplified version. I have x and Y data points and I want to find the area inclosed by the graph between x=2 and x=3. The code is below. It didnt work. Can anyone help me.
clc
clear all
x=[0 1 2 2.5 3 4 5 6] ;
yf=@(x)[0 -1 0 0.10 1 0 -1 0];
y=yf(x);
plot(x,y)
grid on
area_1= integral(yf, x(3), x(4));

Answers (1)

Star Strider
Star Strider on 12 Dec 2016
You cannot use the integral function on data such as you presented. You must use trapz.
Another example:
x=[0 1 2 2.5 3 4 5 6] ;
yf=[0 -1 0 0.10 1 0 -1 0];
y=yf;
plot(x,y)
grid
min_y = min(y);
xidx = find((x >= 2) & (x <= 3));
int_1 = trapz(x(xidx), y(xidx)) % Area From ‘y = 0’
int_2 = trapz(x(xidx), y(xidx)-min_y) % Area From ‘y = min(y)’
int_1 =
0.3
int_2 =
1.3
  2 Comments
friet
friet on 12 Dec 2016
The area above y=0 should be a little bit less than 1. I dont think int_1=0.3 is write? When you use
int_1 = trapz(x(xidx), y(xidx))
you specify the x intervals as,. How can I specify my y interval?
Star Strider
Star Strider on 12 Dec 2016
First, I do not agree that between 2 and 3 the area ‘should be a little bit less than 1. The height of the triangle from 2 to 3 with a height of 1 (from a baseline of 0) would be ½*b*h or 0.5, so it should be a bit less than 0.5, and (with a value of 0.3), it is.
I specify the intervals for both ‘x’ and ‘y’ with respect to the index values in ‘xidx’. Explore the code and the results to see that it is correct.

Sign in to comment.

Categories

Find more on Just for fun in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!