Method: Numo::NArray#diff

Defined in:
lib/numo/narray/extra.rb

#diff(n = 1, axis: -1)) ⇒ Object

Calculate the n-th discrete difference along given axis.

Examples:

x = Numo::DFloat[1, 2, 4, 7, 0]
# => Numo::DFloat#shape=[5]
# [1, 2, 4, 7, 0]

x.diff
# => Numo::DFloat#shape=[4]
# [1, 2, 3, -7]

x.diff(2)
# => Numo::DFloat#shape=[3]
# [1, 1, -10]

x = Numo::DFloat[[1, 3, 6, 10], [0, 5, 6, 8]]
# => Numo::DFloat#shape=[2,4]
# [[1, 3, 6, 10],
#  [0, 5, 6, 8]]

x.diff
# => Numo::DFloat#shape=[2,3]
# [[2, 3, 4],
#  [5, 1, 2]]

x.diff(axis:0)
# => Numo::DFloat#shape=[1,4]
# [[-1, 2, 0, -2]]


951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
# File 'lib/numo/narray/extra.rb', line 951

def diff(n=1,axis:-1)
  axis = check_axis(axis)
  if n < 0 || n >= shape[axis]
    raise ShapeError,"n=#{n} is invalid for shape[#{axis}]=#{shape[axis]}"
  end
  # calculate polynomial coefficient
  c = self.class[-1,1]
  2.upto(n) do |i|
    x = self.class.zeros(i+1)
    x[0..-2] = c
    y = self.class.zeros(i+1)
    y[1..-1] = c
    c = y - x
  end
  s = [true]*ndim
  s[axis] = n..-1
  result = self[*s].dup
  sum = result.inplace
  (n-1).downto(0) do |i|
    s = [true]*ndim
    s[axis] = i..-n-1+i
    sum + self[*s] * c[i] # inplace addition
  end
  return result
end