Last active
August 26, 2024 03:00
-
-
Save pshriwise/67c2ae78e5db3831da38390a8b2a209f to your computer and use it in GitHub Desktop.
Moore-Penrose Pseudo-Inverse Using Eigen
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
| // method for calculating the pseudo-Inverse as recommended by Eigen developers | |
| template<typename _Matrix_Type_> | |
| _Matrix_Type_ pseudoInverse(const _Matrix_Type_ &a, double epsilon = std::numeric_limits<double>::epsilon()) | |
| { | |
| Eigen::JacobiSVD< _Matrix_Type_ > svd(a ,Eigen::ComputeFullU | Eigen::ComputeFullV); | |
| // For a non-square matrix | |
| // Eigen::JacobiSVD< _Matrix_Type_ > svd(a ,Eigen::ComputeThinU | Eigen::ComputeThinV); | |
| double tolerance = epsilon * std::max(a.cols(), a.rows()) *svd.singularValues().array().abs()(0); | |
| return svd.matrixV() * (svd.singularValues().array().abs() > tolerance).select(svd.singularValues().array().inverse(), 0).matrix().asDiagonal() * svd.matrixU().adjoint(); | |
| } |
Author
Thanks for posting this @muttistefano! If I have time I'll try this version in the application where I applied the inverse in this gist to ensure it also has the behavior I'd expect.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi @pshriwise , i tried both versions and they both have problems.
I actually need to use
Eigen::ComputeFullU | Eigen::ComputeFullVcause I need the full matrices of the svd.If it's useful, I can post here a working version, based on the Eigen::BDCSVD class.
If I will have time I will dig more into this.
For now, I will stick to the working version.
I post it here cause if you look up for eigen pseudoinverse you might end up here.
Thanks