Skip to content

Instantly share code, notes, and snippets.

@knugie
Last active June 29, 2016 19:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save knugie/13c1fe02e02cedbbf2d3366b7fb9c99b to your computer and use it in GitHub Desktop.
Save knugie/13c1fe02e02cedbbf2d3366b7fb9c99b to your computer and use it in GitHub Desktop.
Cluster vectors by their similarity defined by a tolerance vector
require 'matrix'
tolerance = Vector[5, 5, 5]
elements = [Vector[2, 1, 4], Vector[20, 100, 25], Vector[21, 98, 21], Vector[1, 2, 3]]
clusters = []
while(elements.any?)
element = elements.pop
cluster, elements = elements.partition do |elem|
diff = tolerance - (elem - element).map(&:abs)
diff.all? { |s| s > 0 }
end
clusters << (cluster << element)
end
clusters.each { |cluster| p cluster }
# [Vector[2, 1, 4], Vector[1, 2, 3]]
# [Vector[20, 100, 25], Vector[21, 98, 21]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment