mercredi 30 janvier 2019

How to write a templated version of this slicing code of Eigen?

I wrote this little piece of code to slice a MatrixXd with a boolean array. I'd like to know how to turn it into a templated version, that works on both matrices and vectors? Any tips? I have not been able to get very far with MatrixBase<Derived>.

#include <Eigen/Dense>
using namespace Eigen;

MatrixXd slice(const MatrixXd & mat, const Array<bool, Dynamic, 1> & ind)
{
    assert(mat.cols() == ind.size());
    int _cols = 0;
    for(int i = 0; i < ind.size(); ++i)
    {
        if(ind[i] == 1)
        {
            _cols += 1;
        }
    }
    int _pos = 0;
    MatrixXd out = MatrixXd::Zero(mat.rows(), _cols);
    for(int i = 0; i < ind.size(); ++i)
    {
        if(ind[i] == 1)
        {
            out.col(_pos) = mat.col(i);
            _pos += 1;
        }
    }
    return out;
}

And usage is like this:

MatrixXd A(4, 4);
A << 1,2,3,4,
     5,6,7,8,
     1,5,6,3,
     9,8,6,5;
VectorXd b(4);
b << 23,-4,1234,3;
cout << A << endl;
cout << (b.array() > 5) << endl;
cout << slice(A, b.array() > 5) << endl;

Output is as such:

1 2 3 4
5 6 7 8
1 5 6 3
9 8 6 5
1
0
1
0
1 3
5 7
1 6
9 6

I'd appreciate if anyone would show me how to do this!

Aucun commentaire:

Enregistrer un commentaire