For completeness, another solution would be to:
- transform X to an eigen array (for coeffwise operations),
- Apply the modulo formula
a%b = a - (b * int(a/b))
C++ code that return an eigen array:
auto mod_array = X.array() - (num * (X.array()/num));
C++ code to get a matrix:
auto mod_matrix = (X.array() - (num * (X.array()/num))).matrix();
Note that, parentheses are important especially in (X.array()/num)
as eigen will optimize (num * X.array()/num)
to X.array()
which is not what we expect.
The first version with eigen array is faster than version with unaryExpr.
The second version with matrix takes about the same time as version with unaryExpr.
If X contains float numbers, you will need to cast X.array()
in (X.array()/num)
to int