Search code examples
c++randomeigenmultinomial

Sample from discrete distribution using weights in Eigen Vector


I have a set of weights in an Eigen::VectorXd and would like to draw samples from the range of indices using these values are probabilities. If weights is a std::vector I can do this:

std::random_device rd;
std::mt19937 rng(rd());
std::discrete_distribution<int> dist(weights.begin(), weights.end());
int val = dist(rng);

What is the best way to do this when weights is an Eigen::VectorXd? Can it be done without copying the vector and without writing the sampler myself?


Solution

  • You could use pointers for Eigen::VectorXd

    std::discrete_distribution<int> dist(weights.data(), weights.data()+weights.size());