Definite Integral Matlab

做~自己de王妃 提交于 2019-12-11 01:16:14

问题


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?

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/18734671/definite-integral-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!