Skip to content

Instantly share code, notes, and snippets.

@javidcf
Last active July 27, 2022 21:21
Show Gist options
  • Save javidcf/25066cf85e71105d57b6 to your computer and use it in GitHub Desktop.
Save javidcf/25066cf85e71105d57b6 to your computer and use it in GitHub Desktop.
Compute the pseudoinverse of a dense matrix with Eigen (C++11)
#include <Eigen/Dense>
template <class MatT>
Eigen::Matrix<typename MatT::Scalar, MatT::ColsAtCompileTime, MatT::RowsAtCompileTime>
pseudoinverse(const MatT &mat, typename MatT::Scalar tolerance = typename MatT::Scalar{1e-4}) // choose appropriately
{
typedef typename MatT::Scalar Scalar;
auto svd = mat.jacobiSvd(Eigen::ComputeFullU | Eigen::ComputeFullV);
const auto &singularValues = svd.singularValues();
Eigen::Matrix<Scalar, MatT::ColsAtCompileTime, MatT::RowsAtCompileTime> singularValuesInv(mat.cols(), mat.rows());
singularValuesInv.setZero();
for (unsigned int i = 0; i < singularValues.size(); ++i) {
if (singularValues(i) > tolerance)
{
singularValuesInv(i, i) = Scalar{1} / singularValues(i);
}
else
{
singularValuesInv(i, i) = Scalar{0};
}
}
return svd.matrixV() * singularValuesInv * svd.matrixU().adjoint();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment