eigenlinspace

Eigen Dynamic-sized matrix verticaly/horizontaly Linspaced?


I'm currently working on a project where i need to be able to create matrix such as :

MatrixXi lin_spaced_horizontaly = 

0 1 2 3 4 ... ncols
0 1 2 3 4 ... ncols
0 1 2 3 4 ... ncols

MatrixXi lin_spaced_verticaly =
0 0 0 
1 1 1 
2 2 2 
3 3 3 
4 4 4
 . . . 
nrows nrows nrows

Currently i am trying things like that :

Eigen::VectorXi v_lin_vec = Eigen::VectorXi::LinSpaced(nrows_, 0, nrows_).transpose
Eigen::MatrixXi v_lin_matrix (nrows_, ncols_);
for (auto i = 0; i<ncols_; i++)
        v_lin_matrix << v_lin_vec;

Eigen::VectorXi h_lin_vec = Eigen::VectorXi::LinSpaced(ncols_, 0, ncols_)
Eigen::MatrixXi h_lin_matrix (nrows_, ncols_);
for (auto i = 0; i<ncols_; i++)
        h_lin_matrix << h_lin_vec;

And I am getting results such as :

v_lin_matrix 
-------------
0 0 0 0 0
1 0 0 0 0
2 0 0 0 0
3 0 0 0 0
4 0 0 0 0

h_lin_matrix
-------------
0 0 0 0 0
1 0 0 0 0
2 0 0 0 0
3 0 0 0 0
4 0 0 0 0

Thanks in advance !


Solution

  • You can use .rowwise().replicate(ncols_) and .colwise().replicate(nrows_) like so:

    Eigen::MatrixXi v_lin_matrix = Eigen::VectorXi::LinSpaced(nrows_, 0, nrows_)
                                         .rowwise().replicate(ncols_);
    Eigen::MatrixXi h_lin_matrix = Eigen::RowVectorXi::LinSpaced(ncols_, 0, ncols_)
                                         .colwise().replicate(nrows_);
    

    Or alternatively:

    Eigen::MatrixXi v_lin_matrix = Eigen::VectorXi::LinSpaced(nrows_, 0, nrows_)
                                         .replicate(1,ncols_);
    Eigen::MatrixXi h_lin_matrix = Eigen::RowVectorXi::LinSpaced(ncols_, 0, ncols_)
                                         .replicate(nrows_,1);
    

    Regarding your use of <<: This is meant to be used in combination with the , operator to initialize a matrix in a single expression, like this:

     Eigen::MatrixXi A(4,ncols_);
     A << row0, row1, row2, row3;
    

    What you wrote will assert at runtime (if you compile without -DNDEBUG, which I strongly recommend until your code is sufficiently tested!)