Last active
July 27, 2022 21:21
-
-
Save javidcf/25066cf85e71105d57b6 to your computer and use it in GitHub Desktop.
Compute the pseudoinverse of a dense matrix with Eigen (C++11)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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