Search code examples
c++eigeneigenvector

Efficient (non-standard) join of two Eigen::VectorXd


I have two Eigen::VectorXd objects, A and B, with the same dimension n.

I want to create a new vector C such that:

  • If B[i] is NaN, C[i] = A[i]
  • Otherwise: C[i] = B[i]

As the application is latency-sensitive, I'd like to avoid making copies of A and B.

Right now I'm using a simple for-loop but I'd like advice on how to implement this in a smart(er) way with Eigen.


Solution

  • Try using select:

    C = (B.array() == B.array()).select(B, A);
    

    The B==B will be true in the values that are non NaN ad false otherwise. For the true values, select returns the first matrix, for false the second.

    As noted below by chtz, a more compact way of writing this would be:

    C = B.array().isNaN().select(A, B);
    

    In terms of performance, this is not vectorized (at least last time I checked), but does not introduce copies of A and B. It's probably the same as what you wrote (as far as I can tell without seeing code).