# Dynamic Sized Identity Matrix in Eigen

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.

• For now, I did something like this MatrixXd temp(n, n); temp.setIdentity(); Mar 9 at 18:32

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.

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