0
$\begingroup$

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.enter image description here

How can I do this in the most quickest way?

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

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

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

enter image description here

and a desired object:

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

ListPlot[desired, Joined -> True, PlotRange -> 5]

enter image description here

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.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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