# How to integrate a plot over specified range?

54 views (last 30 days)
Commented: Rik on 22 Sep 2019
Hi everyone.
I want to integrate a plot over specified range. i have two seperate arrays i.e. x(t) and y(x) which i already have in a plot. now i want to integrate y(x) over x(t) from x(t1) to x(t2), the area under y(x) over this specified range.
To get a better view, let me elaborate with an example:
t = 0:0.1:2*pi;
x = sin(t);
y = cos(x);
Now the question is how to calculate ∫y.dx from x(t=1) to x(t=2).
best regards

MS on 22 Sep 2019
Edited: MS on 22 Sep 2019
You can use the integral function to numerically integrate a function from xmin to xmax. Example:
% define functions
fun_x = @(t) sin(t);
fun_y = @(x) cos(x);
% assign the time interval
t1 = 1;
t2 = 2;
% evaluate function x
xmin = feval(fun_x,t1);
xmax = feval(fun_x,t2);
% integrate
q = integral(fun_y,xmin,xmax);
disp (q);
>>> Output:
0.0434
Hope this helps.

Show 1 older comment
MS on 22 Sep 2019
In this case, you may consider the integral as a summation of the sub-areas under the curve. For example, consider the following criteria. I'm using the functions to create the x and y vectors as an example, but you can import them (assuming you have the data points as you said).
% time vector
t=0:0.1:2*pi;
overall_total = length(t);
x_vector = zeros(1,overall_total);
y_vector = zeros(1,overall_total);
% create the arrays (or get them)
for i=1:overall_total
x_vector(i) = sin(t(i));
y_vector(i) = cos(x_vector(i));
end
% select the points in the x_vector and the y_vector that belongs to the
% interval (t belongs to [t_min,t_max])
t_min = 1;
t_max = 2;
counter =1;
for i=1:overall_total
if ((t(i)>=t_min) && (t(i)<=t_max))
selected_x_vector(counter) = x_vector(i);
selected_y_vector(counter) = y_vector(i);
counter = counter + 1;
end
end
% calculate the sub areas and add them to the summation
selected_total = length(selected_x_vector);
total_area_integral = 0;
for i=2:selected_total
% difference between consecutive x points
width = selected_x_vector(i) - selected_x_vector(i-1);
% average of consecutive y points
length = (selected_y_vector(i) + selected_y_vector(i-1)) / 2;
% calculate sub area
sub_area = width*length;
% add sub area to summation
total_area_integral = total_area_integral + sub_area;
end
% result
disp(total_area_integral);
>>> Output:
0.0434
I get the idea. It is nice and clean, very basic too. I think this solves the problem.
Rik on 22 Sep 2019
It should be possible to replace your last loop with trapz.

Rik on 22 Sep 2019
Edited: Rik on 22 Sep 2019
As you indicated with the tags, using trapz is also an option.
fun_x_of_t=@(t) sin(t);
fun_y_of_x=@(x) cos(x);
fun_y_of_t=@(t) fun_y_of_x(fun_x_of_t(t));
t=linspace(1,2,100);
x=fun_x_of_t(t);
y=fun_y_of_t(t);
trapz(x,y)