2

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.

somebody4
  • 505
  • 4
  • 14

2 Answers2

5

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.

PeterT
  • 7,981
  • 1
  • 26
  • 34
1

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

rafix07
  • 20,001
  • 3
  • 20
  • 33