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.

- 141
- 1
- 3
- 10
-
1the answer i want is the volume of the function f(x,y) in the triangle ABC, with A=(A_x, A_y), B=(B_x, B_y) and C=(C_x, C_y). – user3870075 Nov 06 '16 at 10:45
-
and also the function f(x,y) isn't always equal to 1 – user3870075 Nov 06 '16 at 10:50
-
1Please show the code you have. – Robert Seifert Nov 06 '16 at 10:55
-
+thewaywewalk here is my code: http://pastebin.com/NuXzeLSs – user3870075 Nov 06 '16 at 11:43
2 Answers
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).

- 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
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

- 1
- 1

- 141
- 1
- 3
- 10