Search code examples
c++eigeneigen3

Eigen3: Cast Dynamic Matrix to Static Matrix


is possible to cast a dynamic matrix to a static one and if yes what woud be the best solution? Example:

Eigen::MatrixXd a = Eigen::Matrixxd::Zero(4,4);

to

Eigen::Matrix<double, a.rows(), a.cols()> b = a; //?

Cheers!


Solution

  • From documentation.

    The three mandatory template parameters of Matrix are: Matrix<typename Scalar, int RowsAtCompileTime, int ColsAtCompileTime>.

    RowsAtCompileTime and ColsAtCompileTime are the number of rows and columns of the > matrix as known at compile time

    When you use Eigen::MatrixXd,

    The RowsAtCompileTime and ColsAtCompileTime template parameters can take the special value Dynamic which indicates that the size is unknown at compile time, so must be handled as a run-time variable

    Given that size of a is unknown at compile time, you cannot get value of a.rows().

    Given that you know size of a at compile time, you should use Eigen::Matrix and not Eigen::MatrixXd. However, if you don't know a.rows() or a.cols(), you have to declare b as Eigen::MatrixXd. You cannot use Eigen::Matrix