lib/cumo/narray/extra.rb in cumo-0.2.4 vs lib/cumo/narray/extra.rb in cumo-0.2.5

- old
+ new

@@ -206,10 +206,59 @@ else self.cast(a) end end + + # Iterate over an axis + # @ example + # > a = Cumo::DFloat.new(2,2,2).seq + # > p a + # Cumo::DFloat#shape=[2,2,2] + # [[[0, 1], + # [2, 3]], + # [[4, 5], + # [6, 7]]] + # + # > a.each_over_axis{|i| p i} + # Cumo::DFloat(view)#shape=[2,2] + # [[0, 1], + # [2, 3]] + # Cumo::DFloat(view)#shape=[2,2] + # [[4, 5], + # [6, 7]] + # + # > a.each_over_axis(1){|i| p i} + # Cumo::DFloat(view)#shape=[2,2] + # [[0, 1], + # [4, 5]] + # Cumo::DFloat(view)#shape=[2,2] + # [[2, 3], + # [6, 7]] + + def each_over_axis(axis=0) + unless block_given? + return to_enum(:each_over_axis,axis) + end + if ndim == 0 + if axis != 0 + raise ArgumentError,"axis=#{axis} is invalid" + end + niter = 1 + else + axis = check_axis(axis) + niter = shape[axis] + end + idx = [true]*ndim + niter.times do |i| + idx[axis] = i + yield(self[*idx]) + end + self + end + + # Append values to the end of an narray. # @example # a = Cumo::DFloat[1, 2, 3] # p a.append([[4, 5, 6], [7, 8, 9]]) # # Cumo::DFloat#shape=[9] @@ -985,10 +1034,10 @@ def triu_indices(k=0) if ndim < 2 raise NArray::ShapeError, "must be >= 2-dimensional array" end m,n = shape[-2..-1] - NArray.triu_indices(m,n,k=0) + NArray.triu_indices(m,n,k) end # Return the indices for the uppler-triangle on and above the k-th diagonal. def self.triu_indices(m,n,k=0) x = Cumo::Int64.new(m,1).seq + k