16

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;
andyras
  • 15,542
  • 6
  • 55
  • 77
  • I found an answer, but it would still be nice to have a syntax like I proposed... :) – andyras Nov 18 '14 at 22:33
  • 1
    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 close – vsoftco Nov 18 '14 at 22:45
  • 1
    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. – ggael Nov 19 '14 at 07:18

2 Answers2

26

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);
andyras
  • 15,542
  • 6
  • 55
  • 77
  • 5
    There are also other "init" functions, like `Eigen::Matrix::Zero()` or `Eigen::Matrix::Ones()` http://eigen.tuxfamily.org/dox/group__TutorialAdvancedInitialization.html – vsoftco Nov 18 '14 at 22:42
  • 5
    As well as the `setConstant(val)`, `setOnes()`, `setZero()`, `fill(val)` variants which are more compact to write with less redundancy in your cases. – ggael Nov 19 '14 at 07:16
  • 2
    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 ). – jmcarter9t Jun 24 '16 at 22:03
  • Are the variables `i` and `j` indices or the number of rows and columns? – stackoverflowuser2010 Aug 28 '21 at 02:31
  • @stackoverflowuser2010 It's the number of rows and columns. I just corrected my post based on jmcarter9t's comment. – andyras Aug 28 '21 at 02:36
10

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

andyras
  • 15,542
  • 6
  • 55
  • 77
Jake0x32
  • 1,402
  • 2
  • 11
  • 18