trangular elements

Hi is there a function in matlab that makes it easy to know if you are inside or outside an arbitrarily shaped triangle? I have a triangular mesh from an FE model and I want to interpolate values associated with each node.
/Christoffer

Answers (1)

Jan
Jan on 18 Mar 2011
I you are talking about 2D triangles (otherwise the term "inside" implies a simple projection in the triangle's plane), this is an efficient method:
A, B, C, D are [1 x 2] or [2 x 1] vectors, {A,B,C} is the triangle, R=TRUE if P is inside.
function R = InsideTriangle(A, B, C, P)
r1 = (P(2) - A(2)) * (B(1) - A(1)) - (P(1) - A(1)) * (B(2) - A(2));
r2 = (P(2) - C(2)) * (A(1) - C(1)) - (P(1) - C(1)) * (A(2) - C(2));
r3 = (P(2) - B(2)) * (C(1) - B(1)) - (P(1) - B(1)) * (C(2) - B(2));
R = (r1 * r2 > 0) && (r2 * r3 > 0);

2 Comments

Christoffer
Christoffer on 18 Mar 2011
Took a while to understand the geometry but now I got it. Thanks!
Jan
Jan on 18 Mar 2011
I started with some cross products to compare the orientation of the vectors from A,B,C to P and the vectors AB and AC. Then I boiled the formula down until I got the minimal number of arithmetics operations. Finally the criterion is: Inside==r1,r2,r3 have the same sign.
I'm very curious if somebody can find a leaner method. It is slightly faster to use temporary variables A1=A(1) etc, because this saves 2 indexing operations.

Sign in to comment.

Categories

Asked:

on 18 Mar 2011

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!