简体   繁体   English

将特征向量复制到C数组?

[英]Copy an Eigen vector to a C array?

How do I copy an Eigen vector mesh to a C array r ? 如何将本征向量mesh复制到C数组r

double *r;
typedef Eigen::VectorXd RealVector;
Eigen::Map<RealVector>(r, 1, mesh.cols()) = mesh;

gives an assert from Eigen 从本征给出断言

DenseBase::resize() does not actually allow to resize.

The same message comes from either 相同的消息来自任何一个

Eigen::Map<RealVector>(r, mesh.cols()) = mesh;

or 要么

Eigen::Map<RealVector>(r, mesh.cols(), 1) = mesh;

I need the values to be copied, not just mapped. 我需要复制值,而不仅仅是映射。

Since you did not clarify, I'm speculating three possible errors you could have made: 由于您没有弄清楚,所以我推测您可能已经犯了三个可能的错误:

  • Either your mesh is actually a VectorXd , but then it will always have exactly one column, but potentially multiple rows, ie, you need to write: 您的mesh VectorXd实际上是一个VectorXd ,但是它总是只有一列,但可能有多行,即,您需要编写:

     Eigen::VectorXd::Map(r, mesh.rows()) = mesh; 
  • Or your mesh is a RowVectorXd (ie, having one row and multiple columns). 或者您的meshRowVectorXd (即具有一行和多列)。 Then you need to write: 然后,您需要编写:

     Eigen::RowVectorXd::Map(r, mesh.cols()) = mesh; 
  • If mesh actually is a matrix, you need to decide how to map it to linear memory (ie row-major or column-major). 如果mesh实际上是一个矩阵,则需要决定如何将其映射到线性内存(即行占主导或列占主导)。 This is also possible with Map : 使用Map也可以:

     Eigen::MatrixXd::Map(r, mesh.rows(), mesh.cols()) = mesh; 

You don't have to copy anything actually. 您实际上不必复制任何内容。 You can access the raw data using the .data() member function. 您可以使用.data()成员函数访问原始数据。

#include <Eigen/Core>

int main()
{
  Eigen::VectorXd mesh = Eigen::VectorXd::Random(10);
  double * r = mesh.data();

  r[5] = 0; // writes to mesh directly
  assert(mesh(5) == 0);
}

If you want to copy the data to the pointer, you have to allocate memory, perform the copy and deallocate after use. 如果要将数据复制到指针,则必须分配内存,执行复制并在使用后取消分配。

#include <algorithm>
#include <Eigen/Core>

int main()
{
  Eigen::VectorXd mesh = Eigen::VectorXd::Random(10);
  double * r = new double[mesh.size()];

  std::copy(mesh.data(), mesh.data() + mesh.size(), r);
  assert(r[5] == mesh(5));

  delete[] r;
}

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

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