Search code examples
c++eigen

Is there a way to store thresholding operation output in Eigen (C++)?


In MATLAB, you can create a binary matrix B by thresholding a matrix A as follows:

B = A > threshold

Where threshold is some value. In Eigen for C++, I have been able see similar results, but have faced an inability to assign the output. That is, given

MatrixXd M =
0 1 2
0 1 2
0 1 2

(I know that's not proper initialization but for the sake of the question, go with it)

cout << (M < 1)

produces

1 0 0
1 0 0
1 0 0

but

MatrixXd N = M < 1;

and

M = M < 1;

both give build errors.

Can someone please explain the correct way to save the binary output of this threshold to a variable?


Solution

  • operator< is defined only in the array world, so you have to use .array() to see your MatrixXd as an ArrayXXd (no copy here), and then the result is a array of boolean, so if you want double, then you have to cast explicitly:

    MatrixXd M(3,3);
    M << 0, 1, 2,
         0, 1, 2,
         0, 1, 2;
    MatrixXb Rb = (M.array() < 0.5);                 // result as a matrix of bool
    MatrixXd Rd = (M.array() < 0.5).cast<double>();  // result as a matrix of double