问题
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?
回答1:
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; });
回答2:
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
来源:https://stackoverflow.com/questions/35798698/eigen-matrix-library-coefficient-wise-modulo-operation