(This article was first published on

**Rcpp Gallery**, and kindly contributed to R-bloggers)A previous post showed how to compute eigenvalues using the Armadillo library via RcppArmadillo.

Here, we do the same using Eigen and the RcppEigen package.

```
#include <RcppEigen.h>
// [[Rcpp::depends(RcppEigen)]]
using Eigen::Map; // 'maps' rather than copies
using Eigen::MatrixXd; // variable size matrix, double precision
using Eigen::VectorXd; // variable size vector, double precision
using Eigen::SelfAdjointEigenSolver; // one of the eigenvalue solvers
// [[Rcpp::export]]
VectorXd getEigenValues(Map<MatrixXd> M) {
SelfAdjointEigenSolver<MatrixXd> es(M);
return es.eigenvalues();
}
```

We can illustrate this easily via a random sample matrix.

```
set.seed(42)
X <- matrix(rnorm(4*4), 4, 4)
Z <- X %*% t(X)
getEigenValues(Z)
```

[1] 0.3319 1.6856 2.4099 14.2100

In comparison, R gets the same results (in reverse order) and also returns the eigenvectors.

```
eigen(Z)
```

$values [1] 14.2100 2.4099 1.6856 0.3319 $vectors [,1] [,2] [,3] [,4] [1,] 0.69988 -0.55799 0.4458 -0.00627 [2,] -0.06833 -0.08433 0.0157 0.99397 [3,] 0.44100 -0.15334 -0.8838 0.03127 [4,] 0.55769 0.81118 0.1413 0.10493

Eigen has other *a lot* of other decompositions, see its documentation for more details.

To

**leave a comment**for the author, please follow the link and comment on their blog:**Rcpp Gallery**.R-bloggers.com offers

**daily e-mail updates**about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...