2

I have a bunch of points defined as 2x2 NArrays, and I can't seem to figure out how to avoid iterating. Here's what I have that works:

# Instantiate an example point
point = NArray[[4, 9], [1, 1]]
# Create a blank array to fill
possible_points = NArray.int(2, 2, 16)
possible_points.shape[0].times do |i|
  possible_points[i, 0, true] = point[i, 0]
end

This creates an NArray that looks like

[ [ [ 4, 9 ],
    [ 0, 0 ] ],
  [ [ 4, 9 ],
    [ 0, 0 ] ],
    ...

over all 16 elements in the last dimension.

What I want, however, is something like this:

possible_points[true, 0, true] = point[true, 0]

This iteration sort of defeats the purpose of a numerical vector library. Also it's two lines of code instead of one.

Essentially, the first example (the one that works) lets me assign a single digit over an NArray of size 1,n. The second example (the one that doesn't work) kicks back an error because I'm trying to assign an NArray of size 2 to a location of size 2,n.

Anyone know how I can avoid iterating like this?

acsmith
  • 1,466
  • 11
  • 16
  • your question is not clear. Give us the input data you have and also the expected output. – Arup Rakshit Apr 13 '13 at 19:46
  • what's the array `[true, 0, true]`? give us the algorithm or functional statement - which will tell from your input based on what, what exact output you want. – Arup Rakshit Apr 13 '13 at 20:03
  • the iteration in my initial code block, `possible_points.shape[0].times do |i|`, gives me the correct output. Normally, it's possible with NArray to assign a value over an entire dimension by selecting it with `true`, but this doesn't work for assigning an NArray over an entire dimension. – acsmith Apr 13 '13 at 21:15
  • it could also be that this is just an issue with NArray, and I should take it up as a feature request on the github repo. It's just that NArray is not all that well-documented, so I'm asking here first. – acsmith Apr 13 '13 at 21:17

1 Answers1

2
point = NArray[[4, 9], [1, 1]]
=> NArray.int(2,2): 
[ [ 4, 9 ], 
  [ 1, 1 ] ]

possible_points = NArray.int(2, 2, 16)

possible_points[true,0,true] = point[true,0].newdim(1)

possible_points
=> NArray.int(2,2,16): 
[ [ [ 4, 9 ], 
    [ 0, 0 ] ], 
  [ [ 4, 9 ], 
    [ 0, 0 ] ], 
  [ [ 4, 9 ], 
    [ 0, 0 ] ], 
  [ [ 4, 9 ], 
    [ 0, 0 ] ], 
  [ [ 4, 9 ], 
    [ 0, 0 ] ], 
 ...

To store shape-N narray to shape-NxM narray, convert from shape=[N] to shape=[N,1]. In operations between shape=[N,M] and shape=[N,1], the element at size=1 axis is used repeatedly. This is a general rule of NArray and also applicable to arithmetic operations.

masa16
  • 461
  • 3
  • 5