fabian
fabian

Reputation: 1881

Can I append an Eigen matrix by a vector without copying any data?

Is it possible to append an Eigen vector to an another matrix without copying any data? Given matrix m and vector b I would like to modify matrix m such that m = [m, b] without copying data. Is that possible at all?

An example is:

#include <Eigen/Core>
using namespace Eigen;
int main()
{
    MatrixXd m(2,2);
    m << 0, 1, 2, 3;
    VectorXd b(2);
    b << 4, 5;
    return 0;
}

I tried to work with ggael's wonderful reply to a related question . This questions asks how to create a new matrix without copying data, whilst I would like to modify an existing matrix. I could use conservativeResize to append column b to m but only at the expense of allocating new memory. Does somebody kindly have any ideas how to proceed?

Upvotes: 2

Views: 1785

Answers (1)

chtz
chtz

Reputation: 18827

The only solution I can think of, is to store m and b in the same matrix from the beginning:

Eigen::MatrixXd mb(2,2+1);
Eigen::Ref<Eigen::MatrixXd> m = mb.leftCols(2);
Eigen::Ref<Eigen::VectorXd> b = mb.col(2);

After these lines m and b are read/writable references to blocks of the bigger mb matrix and they stay valid as long as mb is not resized (or destructed). However, you can't easily resize m (you could with a placement-new, but I doubt you really need this).

If you already have data allocated for m and b and want to have their actual data next to each other, you will need to copy something (unless the data was next to each other already).

Upvotes: 1

Related Questions