C++ Eigen - How to combine broadcasting and elementwise operations
Asked Answered
R

1

9

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!

Robyn answered 25/4, 2016 at 19:19 Comment(0)
V
8

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.

Vagary answered 25/4, 2016 at 19:57 Comment(2)
This solved my problem above. While I have another problem for broadcasting. It is possible to perform the broadcasting operation for + and - without the .array() syntax according to the document. Why I need to use the array() method for doing multiplication and division?Robyn
@Robyn To quote the documentation, "The Array class provides general-purpose arrays, as opposed to the Matrix class which is intended for linear algebra." Addition and subtraction are operations that are defined for linear algebra as well (see e.g. Wikipedia), whereas coefficient wise multiplication and division by another matrix or vector are not.Vagary

© 2022 - 2024 — McMap. All rights reserved.