# How to find the index of a facet of a boundary mesh region closest to a given point?

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


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.

Naive solution:

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


{2, 20}

• 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. Feb 14, 2017 at 15:19

You can use the built-in (undocumented) function RegionMeshMeshNearestCellIndex:

nearestcellindex = RegionMeshMeshNearestCellIndex[a, testpoint]

{2, 20}

np = RegionNearest[a, testpoint];

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