Search code examples
c++11vectoreigensquarepiecewise

Piece-wise square of vector, piece-wise product of two vectors in C++ Eigen


Granted that v, a are Eigen::VectorXd vectors with n dimensions, I would like to make the following piece-wise operations:

  • The piece-wise multiplication of v by a, i.e., the vector (a[1]*v[1], ..., a[n]*v[n]), and
  • The piece-wise square of v, i.e., the vector (v[1]*v[1], ..., v[n]*v[n]).

Does Eigen provide methods for the above operations, or do I need to implement them manually? There are certainly very simple, but I would like them to run as fast as possible.


Solution

  • EDIT: Avi's answer is definitely a better solution

    Well, if you get the first one going, the second one is just a particular case where a=v.

    The easiest way of doing the first operation is creating a diagonal matrix from a and doing a normal product.

    Taking a look at the docs, you can use a.asDiagonal().

    About efficiency, perhaps this isn't what you want if you want it to be 'as fast as possible'. In that case, you should measure this against a loop and vector construction to see if there's any practical difference to you.