Search code examples
c++eigen

c++ - How can Eigen do dynamic matrix and vector multiplication?


I'm having trouble to do dynamic matrix and vector dot product and surprisingly, I didn't make it find any solution since Eigen is a prevalent library.

So the code is really simple:

int k = 3;
MatrixXd m;
m.resize(k, k);
ArrayXd a;
a.resize(k);
std::cout << "Dot product: " << m*a << std::endl;

I got error

invalid operands to binary expression ('MatrixXd' (aka 'Matrix') and 'ArrayXd' (aka 'Array')) std::cout << "Dot product: " << m*a << std::endl;

I'm confused if doing dynamic matrix and vector multiplication is feasible. Meanwhile, I found that there is .dot() method for vectors and matrices, so which one to use, * or .dot() for dot product?


Solution

  • You need to have matrices, and not a mix of matrices and arrays. You need to convert a to an array (it's a view, no additional computational cost) with .matrix().

    Try:

    std::cout << "Dot product: " << m*a.matrix() << std::endl;