Skip to content

Instantly share code, notes, and snippets.

@olzhas
Forked from javidcf/pseudoinverse.cpp
Created March 16, 2017 11:43
Show Gist options
  • Save olzhas/eda3160206dd2d17a1714ea05d783af9 to your computer and use it in GitHub Desktop.
Save olzhas/eda3160206dd2d17a1714ea05d783af9 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