Comma initialize a const Eigen matrix

Alec Jacobson

January 14, 2015

weblog/

I've forgotten this a couple times. Here's how to initialize an Eigen matrix's entries while keeping it const and avoiding auxiliary variables:

const Eigen::MatrixXd A = (Eigen::MatrixXd(2,2) << 1,2,3,4).finished();

update: can also use auto:

const auto A = (Eigen::MatrixXd(2,2) << 1,2,3,4).finished();

Using auto with Eigen can be messy, but I've checked that indeed in this case auto expands to Eigen::MatrixXd.