diag.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. #include "diag.h"
  2. #include "verbose.h"
  3. // Bug in unsupported/Eigen/SparseExtra needs iostream first
  4. #include <iostream>
  5. #include <unsupported/Eigen/SparseExtra>
  6. template <typename T>
  7. IGL_INLINE void igl::diag(
  8. const Eigen::SparseMatrix<T>& X,
  9. Eigen::SparseVector<T>& V)
  10. {
  11. // Get size of input
  12. int m = X.rows();
  13. int n = X.cols();
  14. V = Eigen::SparseVector<T>((m>n?n:m));
  15. V.reserve(V.size());
  16. // Iterate over outside
  17. for(int k=0; k<X.outerSize(); ++k)
  18. {
  19. // Iterate over inside
  20. for(typename Eigen::SparseMatrix<T>::InnerIterator it (X,k); it; ++it)
  21. {
  22. if(it.col() == it.row())
  23. {
  24. V.coeffRef(it.col()) += it.value();
  25. }
  26. }
  27. }
  28. }
  29. template <typename T,typename DerivedV>
  30. IGL_INLINE void igl::diag(
  31. const Eigen::SparseMatrix<T>& X,
  32. Eigen::MatrixBase<DerivedV> & V)
  33. {
  34. // Get size of input
  35. int m = X.rows();
  36. int n = X.cols();
  37. V.derived().resize((m>n?n:m),1);
  38. // Iterate over outside
  39. for(int k=0; k<X.outerSize(); ++k)
  40. {
  41. // Iterate over inside
  42. for(typename Eigen::SparseMatrix<T>::InnerIterator it (X,k); it; ++it)
  43. {
  44. if(it.col() == it.row())
  45. {
  46. V(it.col()) = it.value();
  47. }
  48. }
  49. }
  50. }
  51. template <typename T>
  52. IGL_INLINE void igl::diag(
  53. const Eigen::SparseVector<T>& V,
  54. Eigen::SparseMatrix<T>& X)
  55. {
  56. // clear and resize output
  57. Eigen::DynamicSparseMatrix<T, Eigen::RowMajor> dyn_X(V.size(),V.size());
  58. dyn_X.reserve(V.size());
  59. // loop over non-zeros
  60. for(typename Eigen::SparseVector<T>::InnerIterator it(V); it; ++it)
  61. {
  62. dyn_X.coeffRef(it.index(),it.index()) += it.value();
  63. }
  64. X = Eigen::SparseMatrix<T>(dyn_X);
  65. }
  66. template <typename T, typename DerivedV>
  67. IGL_INLINE void igl::diag(
  68. const Eigen::MatrixBase<DerivedV> & V,
  69. Eigen::SparseMatrix<T>& X)
  70. {
  71. assert(V.rows() == 1 || V.cols() == 1);
  72. // clear and resize output
  73. Eigen::DynamicSparseMatrix<T, Eigen::RowMajor> dyn_X(V.size(),V.size());
  74. dyn_X.reserve(V.size());
  75. // loop over non-zeros
  76. for(int i = 0;i<V.size();i++)
  77. {
  78. dyn_X.coeffRef(i,i) += V[i];
  79. i++;
  80. }
  81. X = Eigen::SparseMatrix<T>(dyn_X);
  82. }
  83. #ifndef IGL_HEADER_ONLY
  84. // Explicit template specialization
  85. template void igl::diag<double, Eigen::Matrix<double, -1, -1, 0, -1, -1> >(Eigen::SparseMatrix<double, 0, int> const&, Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&);
  86. template void igl::diag<double>(Eigen::SparseMatrix<double, 0, int> const&, Eigen::SparseVector<double, 0, int>&);
  87. #endif