Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I perform vector addition in Ruby?

Tags:

ruby

How do I perform vector addition in Ruby so that

[100, 100] + [2, 3] 

yields

[102, 103] 

(instead of joining two arrays)?

Or it can be another operator too, such as

[100, 100] @ [2, 3] 

or

[100, 100] & [2, 3]
like image 426
nonopolarity Avatar asked Jun 17 '09 20:06

nonopolarity


People also ask

How do you add two arrays in Ruby?

This can be done in a few ways in Ruby. The first is the plus operator. This will append one array to the end of another, creating a third array with the elements of both. Alternatively, use the concat method (the + operator and concat method are functionally equivalent).


2 Answers

See the Vector class:

require "matrix"

x = Vector[100, 100]
y = Vector[2, 3]
print x + y

E:\Home> ruby t.rb
Vector[102, 103]

See vectorops for additional operations on vectors:

… the following operations work like expected

  v1 = Vector[1,1,1,0,0,0]
  v2 = Vector[1,1,1,1,1,1]

  v1[0..3]
  # -> Vector[1,1,1]

  v1 += v2
  # -> v1 == Vector[2,2,2,1,1,1]

  v1[0..3] += v2[0..3]
  # -> v1 == Vector[2,2,2,0,0,0]

  v1 + 2
  # -> Vector[3,3,3,1,1,1]

See also vectorops.

like image 136
Sinan Ünür Avatar answered Oct 12 '22 10:10

Sinan Ünür


module PixelAddition
  def +(other)
    zip(other).map {|num| num[0]+num[1]}
  end
end

Then you can either create an Array subclass that mixes in the module, or add the behavior to specific arrays like:

class <<an_array
  include PixelAddition
end
like image 24
Chuck Avatar answered Oct 12 '22 10:10

Chuck