Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ;)

like image 234
Poia Avatar asked Feb 05 '23 15:02

Poia


1 Answers

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>(&param[n], n, n);
like image 132
Avi Ginsburg Avatar answered Feb 08 '23 16:02

Avi Ginsburg