Search code examples
c++eigeneigen3

avoid making copy of an eigen block that's repeated used


Is it possible not to make a copy into bounds in the 3rd line below?

Eigen::VectorXd all_bounds(100);
Eigen::VectorXd values(10);
Eigen::VectorXd bounds = all_bounds.segment(20, 10);
values = values.cwiseMin(bounds);
values = values.cwiseMax(-bounds);

One way I can think of is to inline bounds.segment(20, 10) into cwise{Min,Max}() call, but it duplicates code between cwise{Min,Max} calls and becomes ugly when the expression to get bounds is longer than the toy example above.


Solution

  • With C++11 you can just write

    auto bounds = all_bounds.segment(20, 10);
    

    Otherwise, or if you want to avoid the (in combination with Eigen) potentially dangerous auto keyword, you can write

    Eigen::Ref<Eigen::VectorXd> bounds = all_bounds.segment(20, 10);
    

    If all_bounds is read-only, use Eigen::Ref<const Eigen::VectorXd> instead.

    Godbolt-Link: https://godbolt.org/z/OzY759


    Note that in your example, both values and all_bounds were not initialized (I assume just to keep the example brief).