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
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
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.
#include <iostream>
void diff(int params[], int length) {
for (size_t i = 0; i < length - 1; i++) {
std::cout << params[i + 1] - params[i] << " ";
}
}
int main() {
int x[] = { 1,1,2,3,5,8,13,21 };
int length =std::size(x);
diff(x, length);
return 0;
}
Output:
0 1 1 2 3 5 8
Prior to C++20 there is no standard algorithm that resembles Matlabs diff
directly, but you can use std::transform
:
#include <algorithm>
#include <vector>
#include <iostream>
#include <functional>
std::vector<int> diff(const std::vector<int>& x) {
if (x.size()==0) return {};
std::vector<int> result(x.size()-1);
std::transform(x.begin()+1,x.end(),x.begin(),result.begin(),std::minus<int>{});
return result;
}
int main() {
std::vector<int> x{1,3,4,5,6,10};
auto d = diff(x);
for (const auto& e : d) std::cout << e << " ";
}
std::minus<int>{}
is a function object that returns the difference between its parameters. It is used as binary operator with std::transform
to calculate the elementwise difference between x
excluding the first element and x
excluding the last element (for the second input range only the start of the range is passed to std::transform
).
See this answer for the algorithm you can use in C++20.
Very naive implementation:
#include <vector>
#include <iostream>
template <typename T>
std::vector<T> diff(const std::vector<T>& array){
std::vector<T> result;
for(int i = 1; i < array.size(); ++i){
result.push_back(array[i] - array[i-1]);
}
return result;
}
Note: you can also add constraints on type T, feel free to consult C++ documentation.