Add row and column at zero position in Eigen matrix

I have a matrix, for example: C (400 400)

and I would like to increase this matrix with one vector: the row and column of this matrix at the initial index 0 of the matrix, for example:

Matrix C:

3 2 5 4 5 6 7 8 20 

my new vector: 25 5 6 8

Result:

  25 5 6 8 5 3 2 5 6 4 5 6 8 7 8 20 

What is the best way to do this at Eigen? Use .resize() and .set ? thanks for the help

+4
source share
2 answers

The best I can come up with is:

 Eigen::MatrixXd newC(C.rows()+1, C.cols()+1); newC << v.transpose(), v.tail(v.size()-1), C; C.swap(newC); 

This assumes your "new vector" is stored as a column vector in v . After this snippet, the variable newC no longer needed.

+3
source

Although I would use the Jitse method to give you one more choice, here is a solution that is a bit more verbose and might seem better where the parts go:

 Eigen::MatrixXd newC(C.rows()+1, C.cols()+1); newC.topRows<1>() = v.transpose(); newC.leftCols<1>() = v; newC.bottomRightCorner(C.rows(),C.cols()) = C; C.swap(newC) 

Note that this assigns the upper left element twice; if you don't want this, replace the third line with this ugly one:

 newC.topRows<1>().tail(v.size()-1) = v.transpose().tail(v.size()-1); 

As a final note about why we do not use resize : it always discards the contents of your matrix (even when the matrix is โ€‹โ€‹compressed), unless the number of elements remains the same, that is, when you resize MxN size of the matrix (M*k)x(N/k) .

+3
source

All Articles