0
$\begingroup$

I am aware of creating an identity matrix in Eigen if the number of rows and columns are known. How do we create them dynamically when the size is not known? An example would be useful. Thanks.

$\endgroup$
1
  • $\begingroup$ For now, I did something like this MatrixXd temp(n, n); temp.setIdentity(); $\endgroup$ Mar 9, 2022 at 18:32

1 Answer 1

3
$\begingroup$

Off the top of my head (for elements of type double):

int n = 100;
auto mat = Eigen::MatrixXd::Identity(n,n);

This uses the default template parameters Eigen::Dynamic for rows- and cols-sizes, with which you can set the size of the matrix in the constructor.

Why the auto? Eigen::MatrixXd::Identitydoes not yield a dense matrix (consisting of n*n stored doubles), but rather an object that behaves as a matrix but evaluates its element access by an overloaded function such as

auto operator(int i, int j) const { return i==j ? 1.0 : 0.0; }

This is in most applications as good as the dense version, saves memory, and uses optimized versions of, say, matrix multiplication and other operations.

Instead, if you'd assign the identity matrix explicitly to a Eigen::MatrixXd, e.g.

Eigen::MatrixXd mat = Eigen::MatrixXd::Identity(n,n);

you would lose these advantages. Sometimes, however, this is required in order to use the matrix in further algorithms, e.g. in decompositions, etc.

$\endgroup$
2
  • $\begingroup$ This works great and thanks for the detailed answer. Though the one I said in the comment also works. This is much cleaner. $\endgroup$ Mar 10, 2022 at 14:09
  • $\begingroup$ @user1408865: sure, this works, but brings in the disadvantages of the "dense approach". But for most applications, that's no real problem. $\endgroup$
    – davidhigh
    Mar 10, 2022 at 16:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.