-2


let's consider a two dimensional fonction f(x,y)
and tree points A,B,C with ABC a triangle
and i want to integrate the function f over the triangle ABC,
is there a way to do that in matlab?
thank you.

user3870075
  • 141
  • 1
  • 3
  • 10

2 Answers2

2

You can create a new function h(x,y), that returns f(x,y) if (x,y) is inside the polygon, and 0 otherwise.

For instance:

A = [0, 0];
B = [0, 5];
C = [5, 0];

triangleX = [A(1) B(1) C(1)];
triangleY = [A(2) B(2) C(2)];

f = @(x,y) (1);
h = @(x,y) (inpolygon(x, y, triangleX, triangleY) .* f(x,y));

q = integral2(h, min(triangleX), max(triangleX), min(triangleY), max(triangleY)
              'Method', 'iterated')

Outputs (which may be close enough for you):

q =

  12.500070877352647

And another function:

f = @(x,y) (x .* y);
q = integral2(@foo, min(triangleX), max(triangleX), min(triangleY), max(triangleY), 
              'Method', 'iterated')

q =

  26.042038561947592

Notice that the integral2 documentation states:

When integrating over nonrectangular regions, the best performance and accuracy occurs when ymin, ymax, (or both) are function handles. Avoid setting integrand function values to zero to integrate over a nonrectangular region. If you must do this, specify 'iterated' method.

So it'll be better if instead of using the above solution, you write two functions that given an x coordinate, give you the minimal and maximal y coordinates of the polygon (triangle).

Itay
  • 16,601
  • 2
  • 51
  • 72
  • thank you for you suggestion +Itay, i am using the integration over a triangle to calculate the elements of a vector. when i used your code the result is slow – user3870075 Nov 06 '16 at 12:08
  • and for A=[0.7265 1.9468], B=[0.6930 2.0000] and C=[0.6617 1.9468] it gives me this warning: Warning: Minimum step size reached near x = 1.94678. There may be a singularity, or the tolerances may be too tight for this problem. Warning: The integration was unsuccessful. – user3870075 Nov 06 '16 at 12:10
0

I found the correct answer, thanks to this https://math.stackexchange.com/questions/954409/double-integral-over-an-arbitrary-triangle

function r = intm2(f, t)
% f: function 
% t: three points of a triangle
% r: integration of f over t
a = t(1,:);
b = t(2,:);
c = t(3,:);

jg = abs((b(1)-a(1))*(c(2)-a(2))-(c(1)-a(1))*(b(2)-a(2)));
ftilda = @(u,v) f(a(1)+u*(b(1)-a(1))+v*(c(1)-a(1)), a(2)+u*(b(2)-a(2))+v*(c(2)-    a(2)));

fy = @(x) 1-x;
r = jg * integral2(ftilda, 0,1, 0,fy);

end
Community
  • 1
  • 1
user3870075
  • 141
  • 1
  • 3
  • 10