Using the RegionNearest[] function, it is possible to calculate the point, $p_{mesh}$, on a mesh region that is nearest to some input point, $p_{input}$. My question is: how to calculate the (label of the) triangle to which the point $p_{mesh}$ is associated?

For example using trial and error I can work out that triangle number 20 contains the point on the mesh which is nearest to my test point.

a = BoundaryDiscretizeRegion[Ball[{0, 0, 0}, 1], 
   MaxCellMeasure -> {"Length" -> 1}, PrecisionGoal -> 1];
testpoint = {1.0, 0.2, 0.7};
pt = RegionNearest[a, testpoint]
Show[{HighlightMesh[a, Style[{2, 20}, Orange, Opacity[0.5]]], 
  Graphics3D[{Red, PointSize[Large], Point[testpoint]}], 
  Graphics3D[{Blue, PointSize[Large], Point[pt]}]}]

Exampleimage of mesh and nearest points

Is there any built in functionality for this in Mathematica? I can imagine a round about way of doing this by finding in the list of vertices of the mesh, which three points are closest to $p_{mesh}$ and then working out which triangle they are associated to. This seems to be too convoluted somehow. Any ideas would be greatly appreciated.


2 Answers 2


Naive solution:

Catch[If[RegionMember[MeshPrimitives[a, #], pt], Throw[#]] & /@ 
  MeshCellIndex[a, 2]]

{2, 20}

  • 1
    $\begingroup$ This looks good, many thanks! I will wait before accepting to see if there are any other options like undocumented features in the RegionNearest function. $\endgroup$
    – Dunlop
    Feb 14, 2017 at 15:19

You can use the built-in (undocumented) function Region`Mesh`MeshNearestCellIndex:

nearestcellindex = Region`Mesh`MeshNearestCellIndex[a, testpoint]
{2, 20}
np = RegionNearest[a, testpoint];

   Style[nearestcellindex, Orange, Opacity[0.5]], 
   PlotTheme -> "Lines"], 
  Graphics3D[{Red, PointSize[Large], Point[testpoint], 
    Purple, Point @ np, 
    Black, Dashed, Line[{testpoint, np} ]}]}]

enter image description here

  • $\begingroup$ see also: this Q/A $\endgroup$
    – kglr
    Oct 16, 2020 at 23:56

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.