Ben - 1 month ago 26x

C++ Question

I have seen it done before but I cannot remember how to efficiently initialize an

`Eigen::Vector`

`std::vector`

`std::vector<double> v1 = {1.0, 2.0, 3.0};`

Eigen::Vector3d v2; // Do I put it like this in here: v2(v1) ?

v2 << v1[0], v1[1], v1[2]; // I know you can do it like this but

// I am sure i have seen a one liner.

I have perused

Answer

According to Eigen Doc, Vector is a typedef for Matrix, and the Matrix has a constructor with the following signature:

`Matrix (const Scalar *data)`

Constructs a fixed-sized matrix initialized with coefficients starting at data.

And vector reference defines the `std::vector::data`

as:

`std::vector::data T* data(); const T* data() const;`

Returns pointer to the underlying array serving as element storage. The pointer is such that range

`[data(); data() + size())`

is always a valid range, even if the container is empty.

So, you could just pass the vector's data as a `Vector3d`

constructor parameter:

```
Eigen::Vector3d v2(v1.data());
```

Also, as of Eigen 3.2.8, the constructor mentioned above defined as:

```
template<typename _Scalar, int _Rows, int _Cols, int _Options, int _MaxRows, int _MaxCols>
inline Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols>
::Matrix(const Scalar *data)
{
this->_set_noalias(Eigen::Map<const Matrix>(data));
}
```

As you can see, it also uses `Eigen::Map`

, as noted by @ggael and @gongzhitaao.

Source (Stackoverflow)

Comments