A Mixin. To be included in a class with multi-dimension indexing support (such as NArray).
each_subary_at_dims( *dims )
Iterator for each sub-array (not each element) specified by dimensions.
ARGUMENT
RETURN VALUE
POSSIBLE EXCEPTIONS
EXAMPLE
Suppose that you want to do something with 2D sub-arrays in a multi-dimension NArray. First, you include this module as follows:
require "narray" class NArray include NumRu::Misc::MD_Iterators end
And prepare the array if you have not (here, it is 4D):
na = NArray.int(10,2,5,2).indgen!
Then you do the job like this:
na.each_subary_at_dims(0,2){ |sub| ... # do whatever with sub }
This is equivalent to the following:
(0...na.shape[3]).each{|j| (0...na.shape[1]).each{|i| sub = na[0..-1, i, 0..-1, j] ... # do whatever with sub } }
Note that the loop must be nested 3 times when na is a 5D array, if the latter approach is used. On the other hand, it will still require the same single loop with the former.
each_subary_at_dims_with_index( *dims )
Like each_subary_at_dims but the block takes two arguments: subset and the subset specifier (index).
EXAMPLE
Suppose the example above in each_subary_at_dims (EXAMPLE). And suppose that you want to overwrite na with the result you get. You can do it like this:
na.each_subary_at_dims_with_index(0,2){ |sub,idx| result = (sub + 10) / 2 na[*idx] = result }
Here, idx is an Array to be fed in the []= or [] methods with asterisk (ungrouping).