1

I am interested in locating all non-empty intervals in a NArray as tuples of [begin, end] type. So if we have a NArray of a given size and all values at index positions 100 ... 200, 300 ... 400, etc are non-zero, I would like to obtain an array like this: [[100,200], [300,400], etc]. I wonder is there is something in the NArray interface - which unfortunately is under-documented - that can help me? Speed is of cause critical.

Cheers,

Martin

maasha
  • 1,926
  • 3
  • 25
  • 45

1 Answers1

1
$ irb -rnarray
irb> a = NArray[0,1,2,0,0,5,0,7,8,9]
irb> tmp = NArray.new( a.typecode, a.size+2 )
irb> tmp[1..-2] = a
irb> tmp
=> NArray.int(12): 
[ 0, 0, 1, 2, 0, 0, 5, 0, 7, 8, 9, 0 ]

irb> empty = tmp.eq(0)
=> NArray.byte(12): 
[ 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1 ]

irb> beg = (~empty[1..-1] & empty[0..-2]).where
=> NArray.int(3): 
[ 1, 5, 7 ]

irb> fin = (empty[1..-1] & ~empty[0..-2]).where
=> NArray.int(3): 
[ 3, 6, 10 ]

irb> range = NArray[beg,fin].transpose(1,0)
=> NArray.int(2,3): 
[ [ 1, 3 ], 
  [ 5, 6 ], 
  [ 7, 10 ] ]
masa16
  • 461
  • 3
  • 5
  • Excellent! This will do for now. Perhaps a couple of build-in function for dealing with intervals and the intersection of these would be in order? – maasha Oct 20 '11 at 07:06