Performing boolean operations on Eigen arrays

2.5k Views Asked by At

I'm trying to use various boolean operations on Eigen matrices. For example, setting NaN or Inf values to a specific value. Or setting values above or below specific values to something else.

I could loop through each value and perform each boolean operation, but I imagine that there's a chance this could miss out on vectorisation, particularly on my C++98 compiler without automatic vectorisation.

I can use unaryExpr for example

template <int replacementValue>
static float ReplaceNanWithValue(float value)
{
    if (std::isnan(value) == true)
    {
        value = static_cast<float>(replacementValue);
    }
    return value;
}

matrix1 = matrix1 .unaryExpr(std::ptr_fun(ReplaceNanWithValue<1>));

However, as I'm using C++98, I'm using the template argument to limit the value I'm setting the Nan with, to a value that can be represented by an int, as you can't use floats or doubles with this template argument also I'm unable to use this method with values that are determined at runtime rather than compile time. With C++11 I could use an anonymous function to do this

const float MaxValue = pow(n, p);
matrix1 = matrix1.unaryExpr([&MaxValue](float value) { return (value > MaxValue) ? MaxValue : value; };
1

There are 1 best solutions below

5
On BEST ANSWER

An alternative to this could be to use the select function.

const float MaxValue = pow(n, p);
matrix1 = (matrix1.array() > MaxValue).select(MaxValue, matrix1);

However I'm unaware of the performance of this compared with writing a plain loop or C++11 specific solutions such as an anonymous function.