ruby-numo / numo-narray

Ruby/Numo::NArray - New NArray class library
http://ruby-numo.github.io/narray/
BSD 3-Clause "New" or "Revised" License
418 stars 42 forks source link

Boolean indexing #81

Closed v0dro closed 6 years ago

v0dro commented 6 years ago

Would be great to have a boolean indexing scheme similar to matlab instead of having to specify indexes each time.

Something like:

n = NArray.random(8)
n[n.eye(8).bool] = 3

Above code will set all the diagonals of array n to 3.

masa16 commented 6 years ago

Numo::Bit array is used for boolean indexing.

require 'numo/narray'

n = Numo::DFloat.new(8,8).rand
=> Numo::DFloat#shape=[8,8]
[[0.0617545, 0.373067, 0.794815, 0.201042, 0.116041, 0.344032, 0.539948, ...], 
 [0.165089, 0.0508827, 0.108065, 0.0687079, 0.904121, 0.478644, 0.342969, ...], 
 [0.74603, 0.138994, 0.411576, 0.292532, 0.869421, 0.0854984, 0.688965, ...], 
 [0.279215, 0.625155, 0.676329, 0.00687156, 0.0577218, 0.281757, 0.369764, ...], 
 [0.9145, 0.82901, 0.095754, 0.000766433, 0.172175, 0.031881, 0.869624, ...], 
 [0.27822, 0.281593, 0.911101, 0.419566, 0.472129, 0.481009, 0.801525, ...], 
 [0.624016, 0.11052, 0.654895, 0.198015, 0.860828, 0.171934, 0.360198, ...], 
 [0.490398, 0.995591, 0.271669, 0.171815, 0.469158, 0.01212, 0.343877, ...]]

b = n.dup.eye.cast_to(Numo::Bit)
=> Numo::Bit#shape=[8,8]
[[1, 0, 0, 0, 0, 0, 0, 0], 
 [0, 1, 0, 0, 0, 0, 0, 0], 
 [0, 0, 1, 0, 0, 0, 0, 0], 
 [0, 0, 0, 1, 0, 0, 0, 0], 
 [0, 0, 0, 0, 1, 0, 0, 0], 
 [0, 0, 0, 0, 0, 1, 0, 0], 
 [0, 0, 0, 0, 0, 0, 1, 0], 
 [0, 0, 0, 0, 0, 0, 0, 1]]

n[b] = 3

n
=> Numo::DFloat#shape=[8,8]
[[3, 0.373067, 0.794815, 0.201042, 0.116041, 0.344032, 0.539948, 0.737815], 
 [0.165089, 3, 0.108065, 0.0687079, 0.904121, 0.478644, 0.342969, ...], 
 [0.74603, 0.138994, 3, 0.292532, 0.869421, 0.0854984, 0.688965, 0.159977], 
 [0.279215, 0.625155, 0.676329, 3, 0.0577218, 0.281757, 0.369764, ...], 
 [0.9145, 0.82901, 0.095754, 0.000766433, 3, 0.031881, 0.869624, 0.484653], 
 [0.27822, 0.281593, 0.911101, 0.419566, 0.472129, 3, 0.801525, 0.0904871], 
 [0.624016, 0.11052, 0.654895, 0.198015, 0.860828, 0.171934, 3, 0.151675], 
 [0.490398, 0.995591, 0.271669, 0.171815, 0.469158, 0.01212, 0.343877, 3]]
v0dro commented 6 years ago

Ah thank you!