Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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;
like image 691
andyras Avatar asked Nov 18 '14 22:11

andyras


People also ask

How do you initialize a matrix in Eigen?

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.

Is Eigen row or column major?

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.

What is Eigen dense?

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.


1 Answers

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);
like image 80
andyras Avatar answered Oct 08 '22 05:10

andyras