trangular elements
3 views (last 30 days)
Show older comments
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
0 Comments
Answers (1)
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
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.
See Also
Categories
Find more on Matrices and Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!