Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eigen how to concatenate matrix along a specific dimension?

Tags:

c++

eigen

I have two eigen matrices and I would like to concatenate them, like in matlab cat(0, A, B)

Is there anything equivalent in eigen?

Thanks.

like image 981
Ran Avatar asked Feb 01 '14 09:02

Ran


2 Answers

You can use the comma initializer syntax for that.

Horizontally:

MatrixXd C(A.rows(), A.cols()+B.cols()); C << A, B; 

Vertically:

// eigen uses provided dimensions in declaration to determine // concatenation direction MatrixXd D(A.rows()+B.rows(), A.cols()); // <-- D(A.rows() + B.rows(), ...) D << A, B; // <-- syntax is the same for vertical and horizontal concatenation 

For readability, one might format vertical concatenations with whitespace:

D << A,      B; // <-- But this is for readability only.  
like image 92
ggael Avatar answered Sep 19 '22 15:09

ggael


I'd use Eigen's block indexing in a way similar to this post (which concatenates to an existing matrix).

The block indexing avoids the direction ambiguity in the accepted approach, and is pretty compact syntax. The following is equivalent to C = cat(2, A, B) in MATLAB:

MatrixXd C(A.rows(), A.cols()+B.cols()); C.leftCols(A.cols()) = A; C.rightCols(B.cols()) = B; 
like image 43
thclark Avatar answered Sep 22 '22 15:09

thclark