repdiag.cpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #include "repdiag.h"
  2. #ifndef IGL_NO_OPENGL
  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::repdiag(
  8. const Eigen::SparseMatrix<T>& A,
  9. const int d,
  10. Eigen::SparseMatrix<T>& B)
  11. {
  12. int m = A.rows();
  13. int n = A.cols();
  14. // Should be able to *easily* do this in coherent order without
  15. // dynamicsparsematrix
  16. Eigen::DynamicSparseMatrix<T, Eigen::RowMajor>
  17. dyn_B(m*d,n*d);
  18. // Reserve enough space for new non zeros
  19. dyn_B.reserve(d*A.nonZeros());
  20. // loop over reps
  21. for(int i=0;i<d;i++)
  22. {
  23. // Loop outer level
  24. for (int k=0; k<A.outerSize(); ++k)
  25. {
  26. // loop inner level
  27. for (typename Eigen::SparseMatrix<T>::InnerIterator it(A,k); it; ++it)
  28. {
  29. dyn_B.coeffRef(i*m+it.row(),i*n+it.col()) += it.value();
  30. }
  31. }
  32. }
  33. B = Eigen::SparseMatrix<T>(dyn_B);
  34. }
  35. template <typename T>
  36. IGL_INLINE void igl::repdiag(
  37. const Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic> & A,
  38. const int d,
  39. Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic> & B)
  40. {
  41. int m = A.rows();
  42. int n = A.cols();
  43. B.resize(m*d,n*d);
  44. B.array() *= 0;
  45. for(int i = 0;i<d;i++)
  46. {
  47. B.block(i*m,i*n,m,n) = A;
  48. }
  49. }
  50. // Wrapper with B as output
  51. template <class Mat>
  52. IGL_INLINE Mat igl::repdiag(const Mat & A, const int d)
  53. {
  54. Mat B;
  55. repdiag(A,d,B);
  56. return B;
  57. }
  58. #ifndef IGL_HEADER_ONLY
  59. // Explicit template specialization
  60. // generated by autoexplicit.sh
  61. template void igl::repdiag<double>(Eigen::SparseMatrix<double, 0, int> const&, int, Eigen::SparseMatrix<double, 0, int>&);
  62. // generated by autoexplicit.sh
  63. template Eigen::SparseMatrix<double, 0, int> igl::repdiag<Eigen::SparseMatrix<double, 0, int> >(Eigen::SparseMatrix<double, 0, int> const&, int);
  64. #endif
  65. #endif