Search code examples
eigenmatrix-multiplication

Eigen row of a M-N matrix multiply column of a N-M matrix in element wise


I have a matrix

A = a11  a12  a13 
    a21  a22  a23

and another matrix

B = b11  b12 
    b21  b22 
    b31  b32

How can I get the following vector using Eigen?

a11 * b11 + a12 * b21 + a13 * b31
a21 * b12 + a22 * b22 + a23 * b32

Solution

  • You want coefficient-wise multiplication, so you have to use arrays ; because of the dimensions you will also need to transpose, and finally since you want a result of shape (Mx1) you will need a rowwise sum. So that gives you the following :

    auto A = Eigen::Matrix<float, 2, 3>::Random().eval();
    auto B = Eigen::Matrix<float, 3, 2>::Random().eval();
    
    Eigen::Matrix<float, 2, 1> C = (A.array()*B.transpose().array()).rowwise().sum();