Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matrix-vector product like multiplication in Eigen

Tags:

c++

matrix

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

like image 911
Piotrekk Avatar asked Mar 08 '23 04:03

Piotrekk


2 Answers

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();
like image 99
ggael Avatar answered Mar 09 '23 18:03

ggael


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>() );
like image 28
RAM Avatar answered Mar 09 '23 17:03

RAM