Search code examples
c++diffderivative

Is there a simple way to do array differences and approximate array derivatives in C++? (Like the diff() function in matlab)


Matlab code I would like to translate into C++

X = [1 1 2 3 5 8 13 21]; 
Y = diff(X)

output : 0 1 1 2 3 5 8

https://www.mathworks.com/help/matlab/ref/diff.html


Solution

  • C++ calls it std::adjacent_difference.

    int X[8] = {1, 1, 2, 3, 5, 8, 13, 21}; 
    int Y[8];
    
    std::adjacent_difference( std::begin(X), std::end(X), std::begin(Y) );
    

    Note that the first element of the destination is a direct copy of the source. The remaining elements are differences.

    See it work on Compiler Explorer.