Search code examples
c++eigeneigen3clamp

How to perform row-wise clipping of a matrix in Eigen?


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));

Solution

  • You can use broadcasting:

    mat = mat.cwiseMin(minmax.row(1).colwise().replicate(mat.rows()))
             .cwiseMax(minmax.row(0).colwise().replicate(mat.rows()));