2

I need to clip (i.e. clamp) elements in every row of a matrix. Each column has its minimum and maximum specified in a two-row matrix (in first row there are minimums, in the second row there are maximums).

I'm currently using this ugly approach to clip values. Is there a prettier, more performant alternative?

MatrixXf minmax {2, 3};
minmax <<
    0.4, 0.1, 1,   // minimums
    4.8, 4.0, 3.0; // maximums

MatrixXf mat = 5.0f * MatrixXf::Random(5,3);

// clamp each row according to minimums and maximums in minmax
for (int i = 0; i < mat.rows(); i++)
    mat.row(i) = mat.row(i).cwiseMin(minmax.row(1)).cwiseMax(minmax.row(0));
wlcezar
  • 25
  • 4

1 Answers1

0

You can use broadcasting:

mat = mat.cwiseMin(minmax.row(1).colwise().replicate(mat.rows()))
         .cwiseMax(minmax.row(0).colwise().replicate(mat.rows()));
ggael
  • 28,425
  • 2
  • 65
  • 71
  • Thank you, just a quick question (I'm new to Eigen): doesn't replicate() bring performance hit (is memory getting physically moved or is there just an internal change of addressing)? – wlcezar Apr 30 '19 at 10:24
  • No memory allocated, it just returns a proxy. – ggael Apr 30 '19 at 20:52