I am trying to initialize a matrix (using the Eigen library) to have a nonzero value when I create it. Is there a nice way to do this without a for loop?
For example, if I wanted to initialize the whole matrix to 1.0, I would like to do something like:
Eigen::MatrixXd mat(i,j) = 1.0;
or
Eigen::MatrixXd mat(i,j);
mat += 1.0;
(I am used to this type of thing in MATLAB, and it would make Eigen even nicer to use than it already is. I suspect there is a built-in method somewhere that does this, that I have not found.)
A sub-question to this question would be how to set a block of matrix elements to a set value, something ilke:
mat.block(i,j,k,l) = 1.0;
Eigen offers a comma initializer syntax which allows the user to easily set all the coefficients of a matrix, vector or array. Simply list the coefficients, starting at the top-left corner and moving from left to right and from the top to the bottom. The size of the object needs to be specified beforehand.
The default in Eigen is column-major. Naturally, most of the development and testing of the Eigen library is thus done with column-major matrices. This means that, even though we aim to support column-major and row-major storage orders transparently, the Eigen library may well work best with column-major matrices.
The Eigen/Dense header file defines all member functions for the MatrixXd type and related types (see also the table of header files). All classes and functions defined in this header file (and other Eigen header files) are in the Eigen namespace.
As so often happens I found the answer in the docs within thirty seconds of posting the question. I was looking for the Constant
function:
Eigen::MatrixXd mat = Eigen::MatrixXd::Constant(i, j, 1.0);
mat.block(i,j,k,l) = Eigen::MatrixXd::Constant(k, l 1.0);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With