somebody4
somebody4

Reputation: 515

In Eigen c++, how to multiply each row of NxM matrix by a vector of Nx1 scalars?

for example, I have:

Matrix<double,5,2,RowMajor> points;
Matrix<double,5,1> scalars;

What I want is equavalent to:

for(int i=0;i<5;++i){
  points.row(i)*=scalars(i);
}

Are there oneliner that can achieve this?

I alreay tried rowwise and array but cannot get it right.

Upvotes: 3

Views: 2332

Answers (2)

PeterT
PeterT

Reputation: 8284

The one-liner is as follows:

points.array().colwise() *= scalars.array();

Because the Array operations are always component-wise.

I thought that .colwise().cwiseProduct(scalars) should also work, but it apparently doesn't.

Upvotes: 6

rafix07
rafix07

Reputation: 20938

You want to perform multiplication element-wise by cols, such kind of operations are suppoted by Array.

Oneliner version:

std::for_each(points.colwise().begin(),points.colwise().end(),
   [&](auto&& col){ col.array() *= scalars.array().col(0); });

Twoliners version:

points.array().col(0) *= scalars.array().col(0);
points.array().col(1) *= scalars.array().col(0);

Live demo

Upvotes: 1

Related Questions