Multiplication of each matrix column by each vector element using Eigen C++ Library

SergioABP picture SergioABP · Mar 21, 2017 · Viewed 7.9k times · Source

I need to multiply each matrix column by each vector element using Eigen C++ library. I tried colwise without success.

Sample data:

Eigen::Matrix3Xf A(3,2); //3x2
A << 1 2,
     2 2,
     3 5;

Eigen::Vector3f V = Eigen::Vector3f(2, 3);

//Expected result
C = A.colwise()*V;

//C
//2 6,
//4 6,
//6 15
//this means C 1st col by V first element and C 2nd col by V 2nd element.

Matrix A can have 3xN and V Nx1. Meaning (cols x rowls).

Answer

Jacob Panikulam picture Jacob Panikulam · Mar 21, 2017

This is what I would do:

Code

Eigen::Matrix3Xf A(3, 2);  // 3x2
A << 1, 2, 2, 2, 3, 5;

Eigen::Vector3f V = Eigen::Vector3f(1, 2, 3);

const Eigen::Matrix3Xf C = A.array().colwise() * V.array();
std::cout << C << std::endl;

Example output:

 1  2
 4  4
 9 15

Explanation

You were close, the trick is to use .array() to do broadcasting multiplications.

colwiseReturnType doesn't have a .array() method, so we have to do our colwise shenanigans on the array view of A.

If you want to compute the element-wise product of two vectors (The coolest of cool cats call this the Hadamard Product), you can do

Eigen::Vector3f a = ...;
Eigen::Vector3f b = ...;
Eigen::Vector3f elementwise_product = a.array() * b.array();

Which is what the above code is doing, in a columnwise fashion.

Edit:

To address the row case, you can use .rowwise(), and you'll need an extra transpose() to make things fit

Eigen::Matrix<float, 3, 2> A;  // 3x2
A << 1, 2, 2, 2, 3, 5;

Eigen::Vector2f V = Eigen::Vector2f(2, 3);

// Expected result
Eigen::Matrix<float, 3, 2> C = A.array().rowwise() * V.transpose().array();
std::cout << C << std::endl;

Example output:

 2  6
 4  6
 6 15