Eigen matrix library coefficient-wise modulo operation

陌路散爱 提交于 2019-12-08 07:06:45

问题


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:

  1. transform X to an eigen array (for coeffwise operations),
  2. 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!