How can I cluster the list so that elements that are within specified distance or less from each other gather together in the sublist? Thanks.
t = RandomInteger[1000, 50];
FindClusters[ t, DistanceFunction -> ManhattanDistance]
Matbe some other functionlike SplitBy or GatherBy should be used, but how to insert the condition on the radius (two cases - one with the specified region in which to gather elements, and another with specified maximum distance from one another) ?
Hi Al Guy,
I do not have an other idea than using brute force: Increasing the number of clusters, until the desired result is reached.
ClearAll["Global`*"]
maxElemDist[clusters_List] := Max[(Differences /@ (Sort /@ clusters)) /. {} -> Sequence[]]
t = RandomInteger[1000, 50];
(* the goal, e.g.: *)
elemDistLimit = 20;
numberOfClusters = 1;
While[elemDistLimit <= maxElemDist[clusters = FindClusters[t, numberOfClusters]],
numberOfClusters++]
(* result: *)
clusters
(* lets check: *)
maxElemDist[clusters]
Maybe this already helps.
Regards – Henrik
I see. Actually Gather is supposed to do the job but it doesn’t:
t = {17, 9, 29, 23, 1, 32, 14, 21, 11, 24, 2, 7, 31, 16, 22, 5, 3, 18,
20, 25, 30, 26, 12, 8, 15, 13, 27, 19, 4, 10, 6, 28};
Gather[t, (Abs[#1 - #2] <= 1) &]
In this case the should all line up in one sublist. They don’t. Why?
I got the Gather part: it just tests all possible combinations of elements in the sublist, not to neighbors. Any way to change that?
I understand the documentation in a way that Gather collects elements which have some property in common.