Search code examples
c++11eigeneigen3

Eigen Range Initialization


I'm trying to use Eigen3 to generate a 2d float matrix (num_samples, num_ranges) such that each column is a continuously spaced range from [0, num_samples) like [0, 1, 2 ... num_samples - 1].

I'm currently achieving this by creating a similar 2d std::vector with std::iota and then converting that to an Eigen 2d matrix.

Is there a faster and simpler way to do this in Eigen?


Solution

  • If I understood correctly, you want the matrix to be like

    0 0 0 0
    1 1 1 1
    2 2 2 2
    3 3 3 3

    for a 4x4 matrix. For that, you can use a combination of LinSpaced (for a single column) and replicate (to duplicate that column):

    int rows = 5;
    int cols = 4;
    Eigen::MatrixXd m = Eigen::VectorXd::LinSpaced(rows, 0.0, rows - 1).replicate(1, cols);
    std::cout << m;