repdiag.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. #ifndef IGL_NO_OPENGL
  10. // Bug in unsupported/Eigen/SparseExtra needs iostream first
  11. #include <iostream>
  12. #include <unsupported/Eigen/SparseExtra>
  13. template <typename T>
  14. IGL_INLINE void igl::repdiag(
  15. const Eigen::SparseMatrix<T>& A,
  16. const int d,
  17. Eigen::SparseMatrix<T>& B)
  18. {
  19. int m = A.rows();
  20. int n = A.cols();
  21. B.resize(m*d,n*d);
  22. // Reserve enough space for new non zeros
  23. B.reserve(d*A.nonZeros());
  24. // loop over reps
  25. for(int i=0;i<d;i++)
  26. {
  27. // Loop outer level
  28. for (int k=0; k<A.outerSize(); ++k)
  29. {
  30. // loop inner level
  31. for (typename Eigen::SparseMatrix<T>::InnerIterator it(A,k); it; ++it)
  32. {
  33. B.insert(i*m+it.row(),i*n+it.col()) = it.value();
  34. }
  35. }
  36. }
  37. B.makeCompressed();
  38. }
  39. template <typename T>
  40. IGL_INLINE void igl::repdiag(
  41. const Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic> & A,
  42. const int d,
  43. Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic> & B)
  44. {
  45. int m = A.rows();
  46. int n = A.cols();
  47. B.resize(m*d,n*d);
  48. B.array() *= 0;
  49. for(int i = 0;i<d;i++)
  50. {
  51. B.block(i*m,i*n,m,n) = A;
  52. }
  53. }
  54. // Wrapper with B as output
  55. template <class Mat>
  56. IGL_INLINE Mat igl::repdiag(const Mat & A, const int d)
  57. {
  58. Mat B;
  59. repdiag(A,d,B);
  60. return B;
  61. }
  62. #ifdef IGL_STATIC_LIBRARY
  63. // Explicit template specialization
  64. // generated by autoexplicit.sh
  65. template void igl::repdiag<double>(Eigen::SparseMatrix<double, 0, int> const&, int, Eigen::SparseMatrix<double, 0, int>&);
  66. // generated by autoexplicit.sh
  67. template Eigen::SparseMatrix<double, 0, int> igl::repdiag<Eigen::SparseMatrix<double, 0, int> >(Eigen::SparseMatrix<double, 0, int> const&, int);
  68. #endif
  69. #endif