Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eigen: Accessing columns of a matrix by reference

Tags:

c++

eigen

I'm using the Eigen C++ matrix library, and I would like to obtain a reference to a column of a matrix. The documentation says to use matrix_object.col(index), but this appears to be returning an object representing the column, rather than simply a reference to the column inside the original matrix object. I am concerned that this involves unnecessary copying of the elements in that column, as changing a value in the column object does not affect the original matrix.

If anyone is more familiar with Eigen than myself, is it still efficient to use this function to access a column of a matrix? If not, how can I just get a reference to the original column inside the matrix?

like image 263
user1871183 Avatar asked Jan 23 '26 11:01

user1871183


2 Answers

mat.col(i) returns a lightweight, read-write proxy object referencing the column i of mat. There is no copy at all. So you can do:

mat.col(i)(j) = 2;

which is equivalent to mat(j,i)=2; You can also do:

mat.col(i).swap(mat.col(j));

without any extra copy. Maybe in your code you explicitly (or implicitly) copied the proxy column object into a Vector object? like this:

VectorXd col_of_mat = mat.col(j);
like image 63
ggael Avatar answered Jan 25 '26 07:01

ggael


First of all, this can obviously only work with column-major matrices. That's what Eigen defaults to, but you should make it explicit when you rely on it.

Then, to get certainty not to have extra proxy object costs, you may use data() to obtain a plain pointer to the whole matrix storage, and increment it by the right amount. For instance, to access the jth column in an n×n matrix m,

auto jth_column = m.data() + n*j;

http://eigen.tuxfamily.org/dox/TopicStorageOrders.html

like image 34
leftaroundabout Avatar answered Jan 25 '26 05:01

leftaroundabout



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!