简体   繁体   English

C ++:如何将std :: vector转换为Eigen :: MatrixXd?

[英]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. 我有长度(n + n * n)的std::vector<double> param ,我需要将最后(n * n)个元素移到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 ;) 编辑:更好意味着更快;)

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. Roger的回答很好,但是如果您要利用向量化,则Eigen::Map不知道它是否对齐,因此没有向量化。 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);

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. 通过这种方式,可以重用参数存储。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM