Poia Poia - 5 days ago 6
C++ Question

C++: how to convert std::vector to Eigen::MatrixXd?

I have

std::vector<double> param
with (n + n * n) length and I need to move last (n * n) elements to MatrixXd. I did it in this way:

MatrixXd cov(n, n);
for(int i = 0 ; i < n ; ++i) {
for(int c = 0 ; c < n ; ++c) {
cov(i, c) = param(n + i * n + c);
}
}


Is there better way to do this?

Edit: better means faster ;)

Answer

If you guarantee that the vector stores its elements contiguously, the simplest and fastest way is the following:

std::vector<double> param;
//code//
.
.
.
//code//
double *v = &param[n];
Eigen::Map<Eigen::MatrixXd> matrix(v,n + n * n,1);

In this way the memory of param is reused.

Comments