zenzu
zenzu

Reputation: 71

Eigen: Comparing each element of vector with constant

is there a way how to compare each element of a vector with a constant? So far, I am comparing 2D vector Eigen::Vector2d with a constant double tolerance like this:

    if (x(0) > tolerance && x(1) > tolerance)
    {
     ...
    }

I have found the function isApprox() but it did not worked somehow. Is there is a nicer or recommended way on how to do it?

Upvotes: 1

Views: 1253

Answers (2)

Eike
Eike

Reputation: 409

I feel like a good call on this one is to write a simple function:

bool is_componentwise_greater_than(
    Eigen::Ref<Eigen::VectorXd const> const &vector, double lower_bound) {
  for (auto value : vector) {
    if (value <= lower_bound)
      return false;
  }
  return true;
}

The drawback of this way compared to the solution by @Matt is, that for more complicated use cases, using an Eigen expression can be more performant (no idea, if this applies here).

The (in my opinion huge) advantage of such an solution is, that you can see exactly what it does from its usage.

Of course you can also pack Matts solution in an aptly named function to get this advantage. Another advantage is, that with the function I provided you know exactly what it does and never have to wonder, whether using auto with an Eigen type could bite you. I guess it won't and Matt probably knows exactly why. But I (and you?) do not and therefore wouldn't want to rely on it.

Upvotes: 0

Matt
Matt

Reputation: 2802

One way to do this is to use the array method of the Vector class. Like this:

#include <Eigen/Dense>
#include <iostream>

int main(int argc, char * argv[]) {
    Eigen::Vector2d A{ 7.5, 8.2 };
    std::cout << A << '\n';
    auto res = A.array() >= 8.0;
    std::cout << res << '\n';
    if (res.all()) {
        std::cout << "True" << '\n';
    }
    else {
        std::cout << "False" << '\n';
    }

    A(0) = 10.2;
    auto res2 = A.array() >= 8.0;
    std::cout << res2 << '\n';
    if (res2.all()) {
        std::cout << "True" << '\n';
    }
    else {
        std::cout << "False" << '\n';
    }

    return 0;
}

In this case res and res2 are CwiseBinaryOp which contains booleans for each element in A. Use all to find when both are True.

Upvotes: 4

Related Questions