简体   繁体   中英

Matrix from std vector to vector from Eigen/Dense

I try to read out elements from a 3D matrix created using the std c++ dynamic container for vectors. Below is how I initialize my matrix:

typedef vector<vector<vector<ClassA> > > matrix3D;

In my class named "ClassA", I have the following public members:

double a, b, c;

Then in my main file, I fill in the matrix with:

double varA=M_PI; double varB=varA; double varC=varA;

matrix3D[i][j][k].a = varA;

matrix3D[i][j][k].b = varB;

matrix3D[i][j][k].c = varC;

Now when I read the doubles into a vector created using Eigen/Dense library, the type of the vector becomes a matrix:

    Vector3d vectorEigen;
    vectorEigen << matrix3D[i][j][k].a, matrix3D[i][j][k].b, matrix3D[i][j][k].c;

and vectorEigen becomes a variable of the type Eigen::Matrix<double, 3,1,0,3,1>

Does anybody have a clue what I have missed here?

Internally Eigen represents vectors as matrices with only one column. So vectors (just like "ordinary" matrices) are really instances of an Eigen::Matrix template class.

For simplicity towards the programmer however, Eigen uses C++'s typedef to define vector classes that are synonyms for an Eigen::Matrix<> with specific options. For example, the Vector3d type in Eigen is a typedef for a matrix whose elements are double s and that has 3 rows and 1 column:

typedef Matrix<double, 3, 1> Vector3d

The Matrix template class actually has 6 template arguments, the last 3 ones being default arguments. Here is the full signature:

template<typename _Scalar, int _Rows, int _Cols, int _Options, int _MaxRows, int _MaxCols>
class Eigen::Matrix< _Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols >

If the compiler refers to Eigen::Matrix<double, 3,1,0,3,1> in error messages it's talking about an Eigen::Matrix with the following template parameters:

  • _Scalar = double
  • _Rows = 3
  • _Cols = 1
  • _Options = 0 (by default)
  • _MaxRows = _Rows (by default) = 3
  • _MaxCols = _Cols (by default) = 1

So Eigen::Matrix<double, 3,1,0,3,1> is just the full type of Vector3d that the compiler sees after resolving typedef and template arguments.

The type hasn't changed at all, you just use the Vector3d shorthand notation in your code, whereas the compiler refers to it by its explicit type.

If you are just interested in implementing Matrix and Vector using C++, then you can totally ignore my answer.

But, if you just need to use Matrix and Vector, then you can try the Mat and Vec class in OpenCV . And here is a good tutorial about Mat.

In addition, if you don't necessarily need to use C++, then Octave is even more convenient.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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