# Matrix-vector product like multiplication in Eigen

### Tags:

#### 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

911

#### Piotrekk

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

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

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

#### 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>() );
``````
28