pinv.cpp 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. #include "pinv.h"
  2. #include <Eigen/SVD>
  3. #include <limits>
  4. #include <cmath>
  5. template <typename DerivedA, typename DerivedX>
  6. void igl::pinv(
  7. const Eigen::MatrixBase<DerivedA> & A,
  8. typename DerivedA::Scalar tol,
  9. Eigen::PlainObjectBase<DerivedX> & X)
  10. {
  11. Eigen::JacobiSVD<DerivedA> svd(A, Eigen::ComputeFullU | Eigen::ComputeFullV );
  12. typedef typename DerivedA::Scalar Scalar;
  13. const Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic> & U = svd.matrixU();
  14. const Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic> & V = svd.matrixV();
  15. const Eigen::Matrix<Scalar,Eigen::Dynamic,1> & S = svd.singularValues();
  16. if(tol < 0)
  17. {
  18. const Scalar smax = S.array().abs().maxCoeff();
  19. tol =
  20. (Scalar)(std::max(A.rows(),A.cols())) *
  21. (smax-std::nextafter(smax,std::numeric_limits<Scalar>::epsilon()));
  22. }
  23. const int rank = (S.array()>0).count();
  24. X = (V.leftCols(rank).array().rowwise() *
  25. (1.0/S.head(rank).array()).transpose()).matrix()*
  26. U.leftCols(rank).transpose();
  27. }
  28. template <typename DerivedA, typename DerivedX>
  29. void igl::pinv(
  30. const Eigen::MatrixBase<DerivedA> & A,
  31. Eigen::PlainObjectBase<DerivedX> & X)
  32. {
  33. return pinv(A,-1,X);
  34. }
  35. #ifdef IGL_STATIC_LIBRARY
  36. // Explicit template instantiation
  37. // generated by autoexplicit.sh
  38. template void igl::pinv<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&);
  39. #endif