Reputation: 87
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 ;)
Upvotes: 4
Views: 9795
Reputation: 10596
Roger's answer is good, with the exception that if you want to utilize vectorization, the Eigen::Map
doesn't know if it's aligned or not, thus no vectorization. If you want that, you need to make a copy of the data and not just map to it.
Eigen::MatrixXd copiedMatrix = Eigen::Map<Eigen::MatrixXd>(¶m[n], n, n);
Upvotes: 7
Reputation: 368
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 = ¶m[n];
Eigen::Map<Eigen::MatrixXd> matrix(v,n + n * n,1);
In this way the memory of param is reused.
Upvotes: 3