How to access the last element of a column of an Eigen matrix in an efficient method?

Viewed 30

the common method i use is like:

Eigen::MatrixXd mat(3,3);
mat<<1,2,3,
     4,5,6,
     7,8,9;
Eigen::Index len = mat.rows();
mat(len-1,0)=10;
std::cout<<mat(len-1,0);

I'd like to know is there more efficient method to do this.

1 Answers

Well, mat.col(0).tail<1>() or mat.bottomLeftCorner<1,1>() work. However, those give you a 1-sized vector expression or 1x1 sized matrix expression, respectively. So the full expression would be

mat.col(0).tail<1>()[0] = 10;
mat.bottomLeftCorner<1,1>()(0,0) = 10;
std::cout << mat.col(0).tail<1>().value();
std::cout << mat.bottomLeftCorner<1,1>().value();

As far as performance goes, these and your approach should all result in equivalent code. For performance reasons, Eigen doesn't support negative indices to express reverse indices the same way Numpy does, for example, because this would introduce a conditional expression in every indexing operation.

Related