Add column to matrix using Eigen library

This is a fairly simple task, but I could not find the 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) so that then

 mat = 1 1 1 2 1 1 1 2 

What is the best (easiest) way to do this?

Note that this is not a duplicate. How do you make a matrix of vectors in your own? . I do not want to initialize the construction of the matrix, but I join the existing one. Or maybe a trick, how to use comma initialization in this case? The following code failed to execute:

 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 need a temporary variable for such a basic task. Is there a better way?

 Matrix2Xd tmp(2, mat.cols()+1); tmp << mat, vec; mat = tmp; 
+7
source share
1 answer

You can use conservativeResize for this purpose:

 mat.conservativeResize(mat.rows(), mat.cols()+1); mat.col(mat.cols()-1) = vec; 
+15
source

Source: https://habr.com/ru/post/1208742/


All Articles