1

This is a combination of the following previous questions: Apply function to all Eigen matrix element and Set coefficients of an Eigen::Matrix according an arbitrary distribution. Basically I'm trying to generate an Eigen matrix with its coefficients sampled from a Gaussian distribution.

Here is my code to do this(static class method) which returns a rather cryptic error message:

matrix_eig EigenUtil::GaussianNoise(size_t rows, size_t cols,
                                    float mean, float std) {
  matrix_eig m(rows, cols);
  std::mt19937 rng;
  std::normal_distribution<float> nd(mean, std);
  auto sampler = [&]() { return nd(rng); };
  return matrix_eig::Zero(rows, cols).unaryExpr(sampler);
}

Which returns the the error: error:

no type named 'type' in 'std::__1::result_of<(lambda at eigen_util.cpp:101:18) (const float &)>'
  typedef typename std::result_of<T>::type type1;
tangy
  • 3,056
  • 2
  • 25
  • 42
  • 2
    That doesn't look like a unary function, it looks like a nullary one. `std::result_of` is undefined if you can't call the given function with the given arguments. Try `[&](float /*unused*/)` perhaps? – o11c Jun 26 '18 at 21:03

1 Answers1

5

As o11c noticed, this is indeed a nullary-expression, and there is almost the exact same example in the doc. I copied it for convenience:

#include <Eigen/Core>
#include <iostream>
#include <random>
using namespace Eigen;
int main() {
  std::default_random_engine generator;
  std::poisson_distribution<int> distribution(4.1);
  auto poisson = [&] () {return distribution(generator);};
  RowVectorXi v = RowVectorXi::NullaryExpr(10, poisson );
  std::cout << v << "\n";
}
ggael
  • 28,425
  • 2
  • 65
  • 71
  • 1
    While this works correctly on my Mac, it throws an error on Ubuntu 16.04 with `g++ -std=c++11`. /usr/include/eigen3/Eigen/src/Core/CoreEvaluators.h:348:27: error: no match for call to ‘(const main()::) (Eigen::Index&)’ return m_functor(index); ^ abc.cpp:8:23: note: candidate: main():: auto poisson = [&] () {return distribution(generator);}; ^ abc.cpp:8:23: note: candidate expects 0 arguments, 1 provided – tangy Jul 05 '18 at 17:04
  • 1
    You need Eigen 3.3.x. – ggael Jul 06 '18 at 07:15