Search code examples
c++eigeneigen3

Multiplying 1xn Eigen::Array with 2xn Eigen::Array, with each column in the 1xn array behaving like a scalar


I have two Eigen::Array which have the same number of columns. One of them, a, has one row, and the other, b, has two rows. What I want to do, is to multiply every column of b with the entry in the respective column in a, so that it behaves like this:

ArrayXXd result;
result.resizeLike(b);
for (int i=0; i<a.cols(); ++i)
    result.col(i) = a.col(i)[0] * b.col(i);

However, it's part of a rather long expression with several of such multiplications, and I don't want to have to evaluate intermediate results in temporaries. Therefore, I'd rather get an Eigen expression of the above, like

auto expr = a * b;

This, of course, triggers an assertion, because a.rows() != b.rows().

What I tried, which works, is:

auto expr = a.replicate(2,1) * b;

However, the resulting code is very slow, so I hope there's a better option.

Possibly related.


Solution

  • Eigen provides the possibility to use broadcasting for such cases. However, the one-dimensional array should first be converted into a Vector:

    broadcasting operations can only be applied with an object of type Vector

    This will work in your case:

    RowVectorXd av = a;  
    ArrayXXd expr = b.rowwise() * av.array();
    

    Edit

    To avoid a copy of the data into a new vector one can use Map:

    ArrayXXd expr = b.rowwise() * RowVectorXd::Map(&a(0), a.cols()).array();