Pregunta

I'm working on a project in Matlab and need to find the area between two lines (intersecting in a point (xIntersection,yIntersection) in the interval [-1,+1]. So the idea is to subtract the two lines and integrate between [-1, xIntersection] and [xIntersection, +1], sum the results and if it's negative, change its sign.

For details on how I find the intersection of the two lines check this link.

I'm using Matlab's function int(), here a snippet of my code:

xIntersection = ((x_1 * y_2 - y_1 * x_2) * (x_3 - x_4) - (x_1 - x_2) * (x_3 * y_4 - y_3 * x_4) ) / ((x_1 - x_2) * (y_3 - y_4) - (y_1 - y_2) * (x_3 - x_4));

syms x;
integral = int( line 1 - line 2 expression containing x, x, -1, xIntersection) + int( line 1 - line 2 expression containing x, x, xIntersection, 1)
if(integral < 0),
    integral = integral * -1;
end

The problem is that Matlab doesn't return a real value for the integral but instead an expression containing a division, i.e. :

107813370750829368626584124420059/162259276829213363391578010288128

This prevents me from been able to do further operations with the result of integration.

  1. Any idea of why this is the returned value?
  2. Any idea of a possible loophole?
¿Fue útil?

Solución

The area between two curves is equal to the integral of the difference between the "upper curve" and the "lower curve", so you have an incorrect sign in the second integrand.

The main problem is however that you are using symbolic expressions. That means MATLAB will try its very best to give you an exact answer, rather than an approximate one (numerical).

If you want numeric outcomes, use numeric methods:

result = ...
    quadgk( @(x) line1(x) - line2(x), -1, xIntersection) + ...
    quadgk( @(x) line2(x) - line1(x), xIntersection, 1 );

or

result = ...
    quadgk(@(x) abs(line1(x) - line2(x)), -1, +1);

for short :)

I believe integral is the function of choice in newer versions of MATLAB ( > R2010a), but I can't test this.

Otros consejos

I don't neccesarily agree with @Rody on this. In general: if you have the chance, why not get the exact result. If it can be solved, at least you don't need to worry about numerical problems too much.

Simply wrap the result with double as suggested by @thewaywewalk.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top