Matlab integration

119 Views Asked by At

I have a graph. I need to integrate between certain x values. I don't have a function for the graph, the curve came from an array of x values and y values. How do I do this?

1

There are 1 best solutions below

4
On BEST ANSWER

Your best bet is to simply apply some of the basic techniques you (should have) learned in calculus. If you have two data vectors, $x$ and $y$, then you have enough data to apply the midpoint method, the trapezoid method, or any other such method.

For instance, the trapezoid method basically says that the area under the curve between two points $x_n$ and $x_{n+1}$ is approximately equal to $y_n(x_{n+1}-x_{n})+\frac12 (y_{n+1}-y_{n})(x_{n+1}-x_n)$, which is equal to the area of the rectangle formed by the height of $x_n$, and adding the area of the triangle whose base is the distance between $x_n$ and $x_{n+1}$ and whose hypotenuse is the line segment connecting $y_n$ and $y_{n+1}$. This can be converted to Matlab easily:

n = length(x);
S = 0;
for i=1:n-1
    S = S + 1/2*(y(i+1)+y(i))*(x(i+1)-x(i));
end

Or, more succinctly and efficiently,

dY = y(1:end-1)+y(2:end);
dX = x(2:end)-x(1:end-1);
S = 1/2*sum(dY.*dX);