# The nearest object from the array of objects

I need to find the most similar to desired object from the array of objects.

In this case object - something with only numeric values which we must compare(for example below it's x and y coords).

By similarity we mean minimal sum of differences between the corresponding values. How can I do this in the most quickest way?

P.S. Array of objects can be sorted before searching if needed.

• – corey979 Nov 15 '16 at 23:47
• I think it's important for us to understand what your "data structure" is. How are these different objects stored in Mathematica? – march Nov 15 '16 at 23:59
• @corey979 thanks! And where I can find algorithm of this function? – don-prog Nov 16 '16 at 0:00
• Are you using Mathematica software? If not, your question doesn't belong on this site. – m_goldberg Nov 24 '16 at 3:39
• @m_goldberg yes, I already understood it. My fault – don-prog Nov 24 '16 at 3:45

Create some data:

object = RandomReal[{0, 5}, {10, 5}];

Grid @ Partition[ListPlot[#, Joined -> True, PlotRange -> 5] & /@ object, 2]
(* or in a more textbook-style: *)
Grid[Partition[Table[ListPlot[object[[i]], Joined -> True, PlotRange -> 5], {i, 1, Length[object]}], 2]] and a desired object:

desired = RandomReal[{0, 5}, 5];

ListPlot[desired, Joined -> True, PlotRange -> 5] According to the description: "minimal sum of differences between the corresponding values", compute

s = Total /@ (Abs @ Subtract[desired, #] & /@ object)
(* textbook-style: *)
s = Table[Total[Abs[desired - object[[i]]]], {i, 1, Length[object]}]


{8.60733, 6.7376, 8.20597, 5.4877, 9.9549, 10.0675, 8.00134, 10.2252, 10.2552, 13.7893}

Position[s, Min @ s] (* or: Position[s, Min[s]] *)


{{4}}

i.e., the fourth object is the closest to the desired one.

For a more general approach, see Nearest.