'Oder of Elements in Eigen CwiseUnaryOp

I have a scenario in which I want to apply some function on each element of a vector in order. For example, let's assume I want to accumulate each element like this using the unaryExpr function which internally constructs a CwiseUnaryOp:

auto sum = 0.f;
auto accumulate = [&](const float& value) {
  sum += value;
  return sum;
};

Eigen::Array<float, Eigen::Dynamic, 1> result = inputSignal.unaryExpr(accumulate);

Where inputSignal is of type Eigen::Array<float, Eigen::Dynamic, 1>. This works but the code assumes that unaryExpr calls the expression with each element in order of how they are positioned in the one-dimensional array. If, for some reason, Eigen would call these out of order, i.e. starting with the last element or whatever, this code will not do what it is intended to do.

So the question is: Does Eigen somehow guarantee, with which order of elements the function is called? I couldn't find any reference to the order in the documentation. If there is no explicite guarantee, is this still "good practice"? Or are there better alternatives?

A somewhat verbose alternative to that would be to use the standard library instead. This is because the order of elements is guaranteed by using iterators, at least to my understanding.

auto sum = 0.f;
auto accumulate = [&](const float& value) {
  sum += value;
  return sum;
};

Eigen::Array<float, Eigen::Dynamic, 1> result{inputSignal.size()};

std::transform(inputSignal.begin(), inputSignal.end(), result.begin(), accumulate);

But, as you can see, we're forced to split construction of the target array and operation into two expressions. This becomes even clearer when you want to return the result, in which case the example using unaryExpr can construct the output array, apply the expression and return in one line.

Again: this accumulate example is just an example. The actual code calls a function inside the lambda but the important part is that both cases (the provided example and the real scenario) assume that the lambda is called with elements in order.

Thanks!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source