Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

eigen

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!

like image 619
yc2986 Avatar asked Apr 25 '16 19:04

yc2986


1 Answers

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.

like image 87
Avi Ginsburg Avatar answered Nov 14 '22 13:11

Avi Ginsburg