Home > Net >  How can I divide two Eigen::Vector3f by the corresponding elements
How can I divide two Eigen::Vector3f by the corresponding elements

Time:10-05

I need to divide two vectors by the corresponding elements. How can I accomplish this? I couldn't find any good sources. Something like

Eigen::Vector3f v1 = { 10.0f, 10.0f, 10.0f };
Eigen::Vector3f v2 = { 5.0f, 2.0f, 2.0f };
Eigen::Vector3f v3 = v1 / v2;

Expected result:

{ 2.0f, 5.0f, 5.0f }

It says "no operator / matches the operands" for division.

CodePudding user response:

While the builtin matrix (expression) types support common linear algebra operations through overloaded operators (e.g. matrix-vector multiplication), Eigen provides distinct types for component-wise operations; the are called "arrays" and subsume Eigen::Array<...> instantiations as well as array expressions. You can always wrap a matrix into an array expression and vice-versa by the .array() and .matrix() member functions - they don't copy anything, but repackage the underlying data such that array-associated operations can be used for matrices, or matrix-associated operations for arrays. In your case, this would be

const Eigen::Vector3f v1 = { 10.0f, 10.0f, 10.0f };
const Eigen::Vector3f v2 = { 5.0f, 2.0f, 2.0f };
const Eigen::Vector3f v3 = v1.array() / v2.array();

If you don't need the matrix interface at all, you can also use Eigen::Array<...> directly:

const Eigen::Array3f a1 = { 10.0f, 10.0f, 10.0f };
const Eigen::Array3f a2 = { 5.0f, 2.0f, 2.0f };
const Eigen::Array3f a3 = a1 / a2;
  • Related