Eigen3 replicate () for cwiseProduct matrix vector

I have the following code:

Eigen::MatrixXf aMatrix( 3, 5 );
aMatrix <<
1, 0, 1, 0, 1,
0, 1, 0, 1, 0,
1, 1, 1, 1, 1;

Eigen::VectorXf aVector( 5 );
aVector << 3, 4, 5, 6, 7;

cout << aMatrix.cwiseProduct( aVector.replicate( 1, aMatrix.rows() ).transpose() ) << endl;

      

which outputs:

3 0 5 0 7
0 4 0 6 0
3 4 5 6 7

      

Is there a more efficient way to achieve this than using a challenge replicate()

?

+3


source to share


2 answers


Solved (with: How can I apply bsxfun functionality on Eigen? )

They are equivalent:



aMatrix.cwiseProduct( aVector.replicate( 1, aMatrix.rows() ).transpose() )
aMatrix.array().rowwise() * aVector.array().transpose()

      

+4


source


I'm not sure if this is more efficient, but repeated multiplication on a diagonal matrix is ​​another option.

aMatrix * aVector.asDiagonal();



#include <iostream>
#include <Eigen/Dense>    

int main()
{

  Eigen::MatrixXf aMatrix( 3, 5 );
  aMatrix <<
    1, 0, 1, 0, 1,
    0, 1, 0, 1, 0,
    1, 1, 1, 1, 1;

  Eigen::VectorXf aVector( 5 );
  aVector << 3, 4, 5, 6, 7;

  std::cout << aMatrix * aVector.asDiagonal() << std::endl;

  return 0;
}

      

+2


source







All Articles