Today I needed to interleave two vectors, e.g. A = [1,2,3,4]
and B = [5,6,7,8]
then I want to make C = [1,5,2,6,3,7,4,8]
.
In Eigen you can do this using the Map
class:
VectorXi A(4);A<<1,2,3,4;
VectorXi B(4);B<<5,6,7,8;
VectorXi C(A.size()+B.size());
Map<VectorXi,0,InnerStride<2> >(C.data(),A.size()) = A;
Map<VectorXi,0,InnerStride<2> >(C.data()+1,B.size()) = B;
Note that |A.size() - B.size()|
should be at most 1.
Update: Here's how to interleave rows of Eigen matrices:
MatrixXi A(2,3);A<<1,2,3,4,5,6;
MatrixXi B(2,3);B<<7,8,9,10,11,12;
MatrixXi C(A.rows()+B.rows(),A.cols());
Map<MatrixXi,0,Stride<Dynamic,2> >(C.data(),A.rows(),A.cols(),Stride<Dynamic,2>(2*A.rows(),2)) = A;
Map<MatrixXi,0,Stride<Dynamic,2> >(C.data()+1,B.rows(),B.cols(),Stride<Dynamic,2>(2*B.rows(),2)) = B;
Printing these matrices you'd see:
A = [
1 2 3
4 5 6
];
B = [
7 8 9
10 11 12
];
C = [
1 2 3
7 8 9
4 5 6
10 11 12
];
Note: This almost surely only works if you're using column major order.