ndarray icon indicating copy to clipboard operation
ndarray copied to clipboard

Equivalent of numpy.diff function

Open espdev opened this issue 4 years ago • 0 comments

In engineering tasks there is often a need for diff function (calculate the n-th discrete difference along the given axis). numpy contains the function that works with n-d arrays.

I have implemented such function (for n1 difference case and nd-arrays) in my experimental code:

fn diff<'a, T: 'a, D, V>(data: V, axis: Option<Axis>) -> Array<T, D>
    where T: NumOps + ScalarOperand, D: Dimension, V: AsArray<'a, T, D>
{
    let data_view = data.into();
    let axis = axis.unwrap_or(Axis(data_view.ndim() - 1));

    let head = data_view.slice_axis(axis, Slice::from(..-1));
    let tail = data_view.slice_axis(axis, Slice::from(1..));

    &tail - &head
}

It would be nice to have such universal function out of the box (perhaps with n/prepend/append parameters also).

espdev avatar Feb 26 '20 14:02 espdev