Search code examples
c++eigeneigen3

Eigen matrix library coefficient-wise modulo operation


In one of the functions in the project I am working on, I need to find the remainder of each element of my eigen library matrix when divided by a given number. Here is the Matlab equivalent to what I want to do:

mod(X,num)

where X is the dividend matrix and num is the divisor.

What is the easiest way to achieve this?


Solution

  • You can use a C++11 lambda with unaryExpr:

    MatrixXi A(4,4), B;
    A.setRandom();
    B = A.unaryExpr([](const int x) { return x%2; });
    

    or:

    int l = 2;
    B = A.unaryExpr([&](const int x) { return x%l; });