Class: Vector

Inherits:
Array
  • Object
show all
Defined in:
lib/mddb/vector.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.from_mongo(value) ⇒ Object



50
51
52
# File 'lib/mddb/vector.rb', line 50

def self.from_mongo(value)
  value.nil? ? nil : Vector.new(value)
end

.to_mongo(value) ⇒ Object



45
46
47
48
# File 'lib/mddb/vector.rb', line 45

def self.to_mongo(value)
  value = value.respond_to?(:lines) ? value.lines : value
  value.to_a
end

Instance Method Details

#*(v) ⇒ Object



2
3
4
5
6
7
8
# File 'lib/mddb/vector.rb', line 2

def *(v)
  result = []
  if v.is_a? Numeric
    self.each {|b| result.push b*v.to_f}
  end
  Vector.new result
end

#+(v) ⇒ Object



35
36
37
38
39
40
41
42
43
# File 'lib/mddb/vector.rb', line 35

def +(v)
  result = Vector.new
  if v.is_a? Vector
    self.each_index {|b| result.push self[b] + v[b]}
    return result
  else
    raise "expected a Vector, got a #{v.class}"
  end
end

#dimensionsObject



25
26
27
# File 'lib/mddb/vector.rb', line 25

def dimensions
  self.to_a.size
end

#dot(v) ⇒ Object



11
12
13
14
15
16
17
# File 'lib/mddb/vector.rb', line 11

def dot(v)
  result = 0
  if v.is_a? Vector
    self.each_index {|b| result += (self[b] * v[b])}
  end
  result
end

#lengthObject



19
20
21
22
23
# File 'lib/mddb/vector.rb', line 19

def length
  result_squrd = 0
  self.each_index  {|b| result_squrd += self[b]**2}
  result_squrd**0.5
end

#to_sObject



54
55
56
57
58
59
60
61
# File 'lib/mddb/vector.rb', line 54

def to_s
  string = ""
  self.each_with_index do |x,i|
    string = string + x.round(2).to_s.rjust(5, ' ')
    string = string +', ' if i < self.size-1
  end
  return string
end

#unitObject



29
30
31
32
33
# File 'lib/mddb/vector.rb', line 29

def unit
  result = Vector.new
  self.each {|b| result.push b*(1/self.length).to_f}
  result
end