Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Eigen: recursive functions accepting any matrix class

Tags:

c++

eigen

eigen3

I want to have a recursive function

template <typename Derived>
void f(Eigen::MatrixBase<Derived>& m)
{
    size_t blockRows = ...
    size_t blockCols = ...
    ....
    f(m.block(0, 0, blockRows, blockCols));
}

This unfortunately results in an infinite compile time recursion.

The first call would be to

f<Eigen::MatrixBase<Derived> >

The second would be to

f<Eigen::Block<Eigen::MatrixBase<Derived>, ... > >

The third call would be to

f<Eigen::Block<Eigen::Block<Eigen::MatrixBase<Derived>, ... >, ... > >

Every time a block of block is requested.

What is the best practice to implement recursive functions in Eigen, which still work on any Eigen matrix type?

I think, I should use some type, that still wraps the same piece of memory, but is not an expression template and it is evaluated.

like image 576
Sogartar Avatar asked Apr 10 '26 14:04

Sogartar


1 Answers

You can cast your recursive block to an Eigen::Ref to avoid the infinite type instantiation:

Ref<MatrixXd> bl = m.block(0, 0, blockRows, blockCols);
f(bl);

To stay fully generic, you can replace MatrixXd by typename Derived::PlainObject.

like image 122
ggael Avatar answered Apr 23 '26 08:04

ggael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!