1

I want to add a row to a two-dimensional NArray. The way described in NArray 0-7 Tutorial is pretty complex - and I wonder if there is a more simple way.

So if I have two NArrays:

n1 = [[ 0,  1,  2,  3],
      [ 4,  5,  6,  7],
      [ 8,  9, 10, 11],
      [12, 13, 14, 15]]

n2 = [16, 17, 18, 19]

I would like to add n1 and n2 to get n3:

n3 = [[ 0,  1,  2,  3],
      [ 4,  5,  6,  7],
      [ 8,  9, 10, 11],
      [12, 13, 14, 15],
      [16, 17, 18, 19]]

How may this be done?

maasha
  • 1,926
  • 3
  • 25
  • 45

4 Answers4

2
require "narray"

class NArray
  def concat(other)
    shp = self.shape
    shp[1] += 1
    a = NArray.new(self.typecode,*shp)
    a[true,0...-1] = self
    a[true,-1] = other
    return a
  end
end

n1 = NArray[[ 0,  1,  2,  3],
            [ 4,  5,  6,  7],
            [ 8,  9, 10, 11],
            [12, 13, 14, 15]]

n2 = NArray[16, 17, 18, 19]

p n1.concat(n2)
# => NArray.int(4,5):
#    [ [ 0, 1, 2, 3 ],
#      [ 4, 5, 6, 7 ],
#      [ 8, 9, 10, 11 ],
#      [ 12, 13, 14, 15 ],
#      [ 16, 17, 18, 19 ] ]
masa16
  • 461
  • 3
  • 5
1

On looking at the way in the tutorial you mention, it's actually very simple:

  1. Copy the "Stacking together different arrays" class definition into your code (or make a new .rb requiring NArray with this definition; and require your new file into your code instead of NArray)

  2. call n1.vcat n2

Arth
  • 12,789
  • 5
  • 37
  • 69
1

You can also use n3 = n1 + [n2], it works with the example you gave.

Ingolmo
  • 575
  • 3
  • 12
0

You can use the << operator. It will change n1.

n1 << n2

If you don“t want n1 to be changed, you can:

n1.dup << n2
Ricardo Acras
  • 35,784
  • 16
  • 71
  • 112