Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append column to matrix, using Eigen library

Tags:

c++

eigen

It's quite a simple task, but I was not able to find an answer to it:

Using the Eigen library, suppose I have Matrix2Xd mat and Vector2d vec, where

mat = 1 1 1
      1 1 1
vec = 2 2

Now I need something like mat.addCol(vec) such that afterwards

mat = 1 1 1 2
      1 1 1 2

What is the best (simplest) way to accomplish this?

Please note, that this is not a duplicate of How do you make a matrix out of vectors in eigen?. I don't want to initialy construct the matrix but append to an existing one. Or is there maybe a trick, how to use the comma initialization in this case? The following code will fail:

Matrix2Xd mat(2,3);
Vector2d vec;
mat << 1, 1, 1, 1, 1, 1;
vec << 2, 2;

cout << mat << endl;
mat << vec;             // <-- crashes here
cout << mat << endl;

Edit: The following works, but I don't like the need of a temporary variable for such a basic task. Is there a better way?

Matrix2Xd tmp(2, mat.cols()+1);
tmp << mat, vec;
mat = tmp;
like image 279
luator Avatar asked Dec 10 '14 15:12

luator


1 Answers

You can use conservativeResize for that purpose:

mat.conservativeResize(mat.rows(), mat.cols()+1);
mat.col(mat.cols()-1) = vec;
like image 95
ggael Avatar answered Oct 21 '22 06:10

ggael