Cheetah Software  1.0
pseudoInverse.h
Go to the documentation of this file.
1 #include <stdio.h>
2 #include <eigen3/Eigen/LU>
3 #include <eigen3/Eigen/SVD>
4 using namespace std;
5 
6 template <typename T>
7 void pseudoInverse(DMat<T> const& matrix, double sigmaThreshold,
8  DMat<T>& invMatrix) {
9  if ((1 == matrix.rows()) && (1 == matrix.cols())) {
10  invMatrix.resize(1, 1);
11  if (matrix.coeff(0, 0) > sigmaThreshold) {
12  invMatrix.coeffRef(0, 0) = 1.0 / matrix.coeff(0, 0);
13  } else {
14  invMatrix.coeffRef(0, 0) = 0.0;
15  }
16  return;
17  }
18 
19  Eigen::JacobiSVD<DMat<T>> svd(matrix,
20  Eigen::ComputeThinU | Eigen::ComputeThinV);
21  // not sure if we need to svd.sort()... probably not
22  int const nrows(svd.singularValues().rows());
23  DMat<T> invS;
24  invS = DMat<T>::Zero(nrows, nrows);
25  for (int ii(0); ii < nrows; ++ii) {
26  if (svd.singularValues().coeff(ii) > sigmaThreshold) {
27  invS.coeffRef(ii, ii) = 1.0 / svd.singularValues().coeff(ii);
28  } else {
29  // invS.coeffRef(ii, ii) = 1.0/ sigmaThreshold;
30  // printf("sigular value is too small: %f\n",
31  // svd.singularValues().coeff(ii));
32  }
33  }
34  invMatrix = svd.matrixV() * invS * svd.matrixU().transpose();
35 }
typename Eigen::Matrix< T, Eigen::Dynamic, Eigen::Dynamic > DMat
Definition: cppTypes.h:106
void pseudoInverse(DMat< T > const &matrix, double sigmaThreshold, DMat< T > &invMatrix)
Definition: pseudoInverse.h:7