Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

In the function Nearest , I can define my custom function using the DistanceFunction option. e.g:

dist[{u_, v_}, {x_, y_}] := 3 Abs[u - x] + 2 Abs[v - y]

Which I can use like this

Nearest[{ {1.5, .6}, {2, 0}, {1.25, 1.25}}, {0, 0}, DistanceFunction -> dist]

Is it possible to give a user-defined DistanceFunction for RegionNearest in V10? I don't see how to do this.

share|improve this question
This is unrelated to the question at hand, hence a comment. With Nearest you can do this more efficiently if you use distance functions that are already "known". In this case you could transform by scaling the coordinates and use the Manhattan norm, as follows. newpts = Map[{3, 2}*# &, origpts]; Nearest[newpts -> origpts, {0, 0}, DistanceFunction -> "ManhattanDistance"] – Daniel Lichtblau Aug 1 '14 at 21:25
up vote 11 down vote accepted

I don't think there's any way to give RegionNearest a user defined DistanceFunction. I don't see an Option for this. However, you can define your own RegionNearest with custom distance function as follows:

dist[{u_, v_}, {x_, y_}] := Norm[{u, v} - {x, y}]


Clear[q1, q2];

regN[region_, point_] := NArgMin[{dist[point, {q1, q2}], {q1, q2} ∈ region}, {q1, q2}]

We can test that this works like the built-in RegionNearest:

RegionNearest[Disk[], {2, 3}] // N

{0.554700196, 0.832050294}

regN[Disk[], {2, 3}]

{0.55470039, 0.832050166}

Here is a more general definition that includes the DistanceFunction as a third argument and works for any dimension:

regN2[region_, point_, distanceF_] := NArgMin[{distanceF[point, x], x ∈ region}, x]

Here is an interesting distance function:

dist2[x_?VectorQ, y_?VectorQ] /; Length[x] == Length[y] := Total[((x - y) - 
                                                    1.2 Round[(x - y)/1.2])^2]


regN2[Disk[], {2, 3}, dist2]  (* in 2D *)

{-0.4, -0.6}

regN[Sphere[], {2, 3, 1}, dist2]  (* in 3D *)

{0.784464204, 0.588348625, -0.196116827}

Of course you can define distanceF to be anything you want as long as it conforms to a distance definition.

share|improve this answer
Thanks so much, this is helpful. I was hoping there was a built-in way, but this is good enough. Hopefully in future updates, this will be added as an option. – Croy Aug 1 '14 at 23:29

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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