简体   繁体   中英

Matrix-vector product like multiplication in Eigen

I am currently facing this problem. I have two matrixes MatrixXf A:

0.5      0.5      0.5      0.5
0.694496 0.548501 0.680067 0.717111
0.362112 0.596561 0.292028 0.370271
 0.56341 0.642395 0.467179 0.598476

and B

0.713072
0.705231
0.772228
0.767898

I want to multiply them like matrix x vector to achive:

0.5*0.713072      0.5*0.713072      0.5*0.713072      0.5*0.713072
0.694496*0.705231 0.548501*0.705231 0.680067*0.705231 0.717111*0.705231
0.362112*0.772228 0.596561*0.772228 0.292028*0.772228 0.370271*0.772228
 0.56341*0.767898 0.642395*0.767898 0.467179*0.767898 0.598476*0.767898

Is there an option to do that in Eigen? How can do that a simply way? http://mathinsight.org/matrix_vector_multiplication

This has been asked so many times, you want a scaling:

MatrixXf A;
VectorXf B;
MatrixXf res = B.asDiagonal() * A;

or using broadcasting:

res = A.array().colwise() * B.array();

In short you want to do an element-wise product between each column of A and vector B .

There are at least two ways of accomplishing this:

  • iterate over each column of A to do an element-wise product with B (in eigen referred to as coefficient-wise product)
  • replicate your B vector into a matrix with the same size as A and perform an element-wise product between A and the new matrix obtained from vector B .

Here's a quick and dirty example based on Eigen's cwiseProduct() and replicate() functions:

auto C = A.cwiseProduct( B.replicate<1,4>() );

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