rubynarray

Avoiding iterating over NArray


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?


Solution

  • 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.