views:

62

answers:

2

Hi,

I would like to populate an 2 dimensional array, from a vector.

I think the best way to explain myself is to put some examples (with a array of [3,5] length).

When vector is: [1, 0]

[
  [4, 3, 2, 1, 0],
  [4, 3, 2, 1, 0],
  [4, 3, 2, 1, 0]
]

When vector is: [-1, 0]

[
  [0, 1, 2, 3, 4],
  [0, 1, 2, 3, 4],
  [0, 1, 2, 3, 4]
]

When vector is: [-2, 0]

[
  [0, 0, 1, 1, 2],
  [0, 0, 1, 1, 2],
  [0, 0, 1, 1, 2]
]

When vector is: [1, 1]

[
  [2, 2, 2, 1, 0],
  [1, 1, 1, 1, 0],
  [0, 0, 0, 0, 0]
]

When vector is: [0, 1]

[
  [2, 2, 2, 2, 2],
  [1, 1, 1, 1, 1],
  [0, 0, 0, 0, 0]
]

Have you got any ideas, a good library or a plan? Any comments are welcome. Thanks.

Note: I consulted Ruby "Matrix" and "Vector" classes, but I don't see any way to use it in my way...

Edit: In fact, each value is the number of cells (from the current cell to the last cell) according to the given vector.

If we take the example where the vector is [-2, 0], with the value *1* (at array[2, 3]):

array = [
  [<0>, <0>, <1>, <1>, <2>],
  [<0>, <0>, <1>, <1>, <2>],
  [<0>, <0>, <1>, *1*, <2>]
]

... we could think such as:

The vector [-2, 0] means that -2 is for cols and 0 is for rows. So if we are in array[2, 3], we can move 1 time on the left (left because 2 is negative) with 2 length (because -2.abs == 2). And we don't move on the top or bottom, because of 0 for rows.

A: 

ok i am a little confused but i am going to take a shot in the dark

What you want is to run through every point in the array and call a function that would calculate the value at that position

so we have loop i loop j array[i,j]=Vectorfunction(i,j,vector); next j next i

function(i,j,vector) Here i am guessing you somehow use the position in the array, and the slope of the line defined by the vector. What that is i can't extract from the data, but i am sure such a function exists.
Most likely this involves arccos to get the angle. and then return i*arcsin+j+arccos

Andrey
A: 

It's quite easy to achieve this:

require 'matrix'

def build(rows, cols, vector)
  Matrix.build(rows, cols){|i, j| vector.inner_product([cols-j-1, rows-i-1]) }
end

build(3, 5, Vector[1, 0]) # => your first example
# ...
build(3, 5, Vector[0, 1]) # => your last example

You will need the latest Matrix library which introduces Matrix.build.

Note: I find your examples a bit odd, and the third one even stranger. Looks like we have to divide by the vector you give, unless it's 0? Anyways, just adapt the block to the formula you need.

Marc-André Lafortune
Wow! Seems to be amazing. I'm gonna updating to 1.9 and trying your code. Many thanks!!
Zag zag..
You can also just copy the library and include it instead of the builtin one. I will backport the lib to the 1.8 line as soon as I get a chance.
Marc-André Lafortune