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

2

17

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;
Am answered 18/11, 2014 at 22:26 Comment(3)
I found an answer, but it would still be nice to have a syntax like I proposed... :)Am
Close to what you want: multiply the scalar by Eigen::MatrixXd::Ones(rows,cols), like: Eigen::MatrixXd mat(3,3) = 1.5 * Eigen::MatrixXd::Ones(3,3) It's not quite like MATLAB, but closeThenna
The syntax you tried works with Eigen::Array but not with linear algebra matrices because in this case a scalar value should rather be assimilated as the identity matrix times this scalar value.Bradbradan
A
27

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);
Am answered 18/11, 2014 at 22:32 Comment(5)
There are also other "init" functions, like Eigen::Matrix::Zero() or Eigen::Matrix::Ones() eigen.tuxfamily.org/dox/…Thenna
As well as the setConstant(val), setOnes(), setZero(), fill(val) variants which are more compact to write with less redundancy in your cases.Bradbradan
Be cautious of the parameters for block and Eigen::MatrixXd::Constant. ( i, j ) is the starting position of the block, and ( k, l ) is the size of the block. So, I think in the second example the ( i, j ) pair on the right hand side should be ( k,l ).Bug
Are the variables i and j indices or the number of rows and columns?Lester
@Lester It's the number of rows and columns. I just corrected my post based on jmcarter9t's comment.Am
L
12

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

Ldopa answered 20/11, 2014 at 5:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.