andyras
andyras

Reputation: 15930

How should I initialize the contents of a large matrix in Eigen?

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;

Upvotes: 17

Views: 35977

Answers (2)

andyras
andyras

Reputation: 15930

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);

Upvotes: 27

Jake0x32
Jake0x32

Reputation: 1432

Eigen::MatrixXd::Ones(), Eigen::MatrixXd::Zero() and Eigen::MatrixXd::Random() can all give you what you want, creating the Matrix in a dynamic way.

Upvotes: 12

Related Questions