Search code examples
eigen3

Write return variable to external data


Suppose that I have

size_t n = 100;
Eigen::MatrixXd A(n, n);
std::vector<double> x(n);
std::vector<double> b(n);

Eigen::VectorXd B = A * Eigen::Map<const Eigen::VectorXd>(x.data(), n);
std::copy(B.data(), B.data() + n, b.begin());

My question is: can I write directly to the memory of the 'external' b ?


Solution

  • Eigen::Map with a non-const template parameter is writable, so you can simply write:

    Eigen::Map<Eigen::VectorXd>(b.data(), b.size()).noalias()
          = A * Eigen::Map<const Eigen::VectorXd>(x.data(), n);
    

    The .noalias() is important to tell Eigen that the left-hand-side does not alias any part of the right-hand-side (otherwise, it would evaluate to a temporary first, producing almost identical instructions to your original code).