Class: SparseVector

Inherits:
Object
  • Object
show all
Defined in:
lib/lite/sparsevect.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attr_map) ⇒ SparseVector

Returns a new instance of SparseVector.



6
7
8
# File 'lib/lite/sparsevect.rb', line 6

def initialize( attr_map )
  @attr = attr_map
end

Instance Attribute Details

#attrObject

Returns the value of attribute attr.



4
5
6
# File 'lib/lite/sparsevect.rb', line 4

def attr
  @attr
end

Instance Method Details

#+(v) ⇒ Object



18
19
20
# File 'lib/lite/sparsevect.rb', line 18

def +(v)
  SparseVector.new( Set.new( v.attr.keys + @attr.keys ).inject( { } ) { |a,c| a[c] = (@attr.has_key?(c) ? @attr[c] : 0) + (v.attr.has_key?(c) ? v.attr[c] : 0); a } )
end

#-(v) ⇒ Object



14
15
16
# File 'lib/lite/sparsevect.rb', line 14

def -(v)
  SparseVector.new( Set.new( v.attr.keys + @attr.keys ).inject( { } ) { |a,c| a[c] = (@attr.has_key?(c) ? @attr[c] : 0) -  (v.attr.has_key?(c) ? v.attr[c] : 0); a } )
end

#dist(v) ⇒ Object



10
11
12
# File 'lib/lite/sparsevect.rb', line 10

def dist( v )
  Math.sqrt( Set.new( @attr.keys + v.attr.keys ).inject(0){|d,k|  u_i = (@attr.has_key? k) ? @attr[k] : 0; v_i =  (v.attr.has_key? k) ? v.attr[k] : 0; d + (u_i-v_i)*(u_i-v_i) } )       
end

#mult_scalar(c) ⇒ Object



22
23
24
# File 'lib/lite/sparsevect.rb', line 22

def mult_scalar( c )
  SparseVector.new( @attr.inject( { } ){ |a, kv| a[ kv.first ] = kv.last * c; a })
end