I am trying to compute the shortest distance between a point and a triangle in 3D

distance[point_, {p1_, p2_, p3_}] := Module[{p, s, t, sol},
  p = s*p1 + (1 - s)*(t*p2 + (1 - t)*p3);
  MinValue[{(point - p).(point - p),
   0 <= s <= 1, 0 <= t <= 1}, {s, t}]];

but it seems to be quite slow, is there any way to make it faster?

  • $\begingroup$ As I unfortunately do not know your intended application this may not work for your purposes, however I would suggest to redefine your triangle as a hyperplane and use LeastSquares[]. This is as a built in function much faster compared to the iteration you have designed here. $\endgroup$
    – Sander
    May 27, 2014 at 3:20

1 Answer 1


Well, you can use the undocumented RegionDistance which does exactly this as follows: (This answer, as written, only works for V9 as noted by Oska, for V10 see update below)

here is a triangle in 3D

region = Polygon[{{0, 0, 0}, {1, 0, 0}, {0, 1, 1}}];


Mathematica graphics

Now suppose you want to find the shortest distance from the point {1, 1, 1} in 3D to this triangle just do the following:

Load the Region context



RegionDistance[region, {1, 1, 1}]

Mathematica graphics

As a bonus, you can get the exact point on the triangle that is closest to the given point as follows:

RegionNearest[region, {1, 1, 1}]

Mathematica graphics

Visualize it

Graphics3D[{region, Darker@Green, PointSize[0.03], Point[{1, 1, 1}], 
  Red, PointSize[0.03], Point[{1/3, 2/3, 2/3}]}]

Mathematica graphics

Update for Version 10

The above undocumented functions used in this answer now works out of the box in V10 so no need to load the Region context as I did above. Otherwise everything works as is. Also, now you can use the new Triangle function in place of Polygon above.

  • 2
    $\begingroup$ For what reasons all of these Graphics functions are undocumented..? $\endgroup$
    – Öskå
    May 26, 2014 at 9:25
  • $\begingroup$ @Öskå, I have no idea :). They seem to be very useful functions from what I can tell. $\endgroup$
    – RunnyKine
    May 26, 2014 at 9:26
  • 1
    $\begingroup$ @RunnyKine I tested your code and gain 50 times faster speed, thanks so much for your help $\endgroup$
    – tintin
    May 26, 2014 at 10:41
  • $\begingroup$ @tintin. Glad I could help. $\endgroup$
    – RunnyKine
    May 26, 2014 at 14:08
  • $\begingroup$ @RunnyKine - Where can I find other undocumented Graphics functions? $\endgroup$
    – eldo
    May 26, 2014 at 14:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.