Search code examples
c++eigen

C++ Eigen - How to combine broadcasting and elementwise operations


I have a MatrixXf variable and a VectorXf variable. I would like to perform a rowwise division using the Vector on my Matrix. Is it possible to do something like this?

#include <iostream>
#include "Eigen/Dense"
using namespace std;
using namespace Eigen;

int main() {
    MatrixXf mat(3, 2);
    mat << 1, 2,
           3, 4,
           5, 6;
    VectorXf vec(2);
    vec << 2, 3;
    mat = mat.rowwise() / vec;
    cout << mat << endl;
    return 0;
}

I am expecting to get a matrix with value [0.5, 0.667; 1.5, 1.333; 2.5, 2].

Thank you very much!


Solution

  • You need to use the matrix and vector as arrays (and not linear algebra objects, see docs). To do so, you would rewrite the relevant line as:

    mat = mat.array().rowwise() / vec.transpose().array();
    cout << mat << endl; // Note that in the original this was vec
    

    The transpose is needed as the VectorXf is a column vector by definition, and you wanted a row vector.