I am looking for the distance between the spatial median of a subset of points to all original points in the set preferences to model group decision making. I can build a for loop to return the subsets spatial medians but am having trouble extracting the optimized distances. Any help is greatly appreciated.

n = 5
preferences = RandomVariate[NormalDistribution[5, 2], {n, 2}]
dtotal[f_] := Total[Sqrt[Total[(Transpose[f] - {x, y})^2]]]
sodtotal = FindMinimum[dtotal[preferences], {x}, {y}]
sopt = {x /. sodtotal[[2]], y /. sodtotal[[2]]}
sodist = sodtotal[[1]]
prefsub = Subsets[preferences, {1, n}]
subdtotal = Map[dtotal, Subsets[preferences, {1, n}]]
subopt = {}
For[i = 1, i <= Length[subdtotal], i++, 
 subopt = Append[
   subopt, {x /. FindMinimum[subdtotal[[i]], {x}, {y}][[2]], 
    y /. FindMinimum[subdtotal[[i]], {x}, {y}][[2]]}]]

Creating Lists From Loops How do I find the Euclidean distance between one point and all the points in a list?

  • $\begingroup$ I think it should look something like subsetdist = {} For[i = 1, i <= Length[subdtotal], i++, subsetdist = Append[subsetdist, {FindMinimum[subdtotal[[i]], {x}, {y}, [[1]]]}]] but I am really trying to get away from this For loop. $\endgroup$ Nov 2 '17 at 20:42
  • $\begingroup$ a bit aside but NMinimize works better here instead of FindMinimum $\endgroup$
    – george2079
    Nov 2 '17 at 21:20
  • $\begingroup$ Thanks I will change them. $\endgroup$ Nov 2 '17 at 21:29

You can replace your subopt initialization and the For loop with:

subopt = {x, y} /. FindMinimum[#, {x}, {y}][[2]] & /@ subdtotal

Or using Map explicitly

{x, y} /. Map[FindMinimum[#, {x}, {y}][[2]] &, subdtotal]
  • $\begingroup$ Thank you that Map function replaces the loop very well. I was hoping to use the Nminimize function for the distance from each point in subopt to all points in preferences. $\endgroup$ Nov 2 '17 at 21:25

Your Answer

