diag.cpp 2.2 KB

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