repdiag.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. // This file is part of libigl, a simple c++ geometry processing library.
  2. //
  3. // Copyright (C) 2013 Alec Jacobson <alecjacobson@gmail.com>
  4. //
  5. // This Source Code Form is subject to the terms of the Mozilla Public License
  6. // v. 2.0. If a copy of the MPL was not distributed with this file, You can
  7. // obtain one at http://mozilla.org/MPL/2.0/.
  8. #include "repdiag.h"
  9. #include <vector>
  10. template <typename T>
  11. IGL_INLINE void igl::repdiag(
  12. const Eigen::SparseMatrix<T>& A,
  13. const int d,
  14. Eigen::SparseMatrix<T>& B)
  15. {
  16. using namespace std;
  17. using namespace Eigen;
  18. int m = A.rows();
  19. int n = A.cols();
  20. vector<Triplet<T> > IJV;
  21. IJV.reserve(A.nonZeros()*d);
  22. // Loop outer level
  23. for (int k=0; k<A.outerSize(); ++k)
  24. {
  25. // loop inner level
  26. for (typename Eigen::SparseMatrix<T>::InnerIterator it(A,k); it; ++it)
  27. {
  28. for(int i = 0;i<d;i++)
  29. {
  30. IJV.push_back(Triplet<T>(i*m+it.row(),i*n+it.col(),it.value()));
  31. }
  32. }
  33. }
  34. B.resize(m*d,n*d);
  35. B.setFromTriplets(IJV.begin(),IJV.end());
  36. // Q: Why is this **Very** slow?
  37. //int m = A.rows();
  38. //int n = A.cols();
  39. //B.resize(m*d,n*d);
  40. //// Reserve enough space for new non zeros
  41. //B.reserve(d*A.nonZeros());
  42. //// loop over reps
  43. //for(int i=0;i<d;i++)
  44. //{
  45. // // Loop outer level
  46. // for (int k=0; k<A.outerSize(); ++k)
  47. // {
  48. // // loop inner level
  49. // for (typename Eigen::SparseMatrix<T>::InnerIterator it(A,k); it; ++it)
  50. // {
  51. // B.insert(i*m+it.row(),i*n+it.col()) = it.value();
  52. // }
  53. // }
  54. //}
  55. //B.makeCompressed();
  56. }
  57. template <typename T>
  58. IGL_INLINE void igl::repdiag(
  59. const Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic> & A,
  60. const int d,
  61. Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic> & B)
  62. {
  63. int m = A.rows();
  64. int n = A.cols();
  65. B.resize(m*d,n*d);
  66. B.array() *= 0;
  67. for(int i = 0;i<d;i++)
  68. {
  69. B.block(i*m,i*n,m,n) = A;
  70. }
  71. }
  72. // Wrapper with B as output
  73. template <class Mat>
  74. IGL_INLINE Mat igl::repdiag(const Mat & A, const int d)
  75. {
  76. Mat B;
  77. repdiag(A,d,B);
  78. return B;
  79. }
  80. #ifdef IGL_STATIC_LIBRARY
  81. // Explicit template specialization
  82. // generated by autoexplicit.sh
  83. template void igl::repdiag<double>(Eigen::SparseMatrix<double, 0, int> const&, int, Eigen::SparseMatrix<double, 0, int>&);
  84. // generated by autoexplicit.sh
  85. template Eigen::SparseMatrix<double, 0, int> igl::repdiag<Eigen::SparseMatrix<double, 0, int> >(Eigen::SparseMatrix<double, 0, int> const&, int);
  86. #endif