for_each.h 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #ifndef IGL_FOR_EACH_H
  2. #define IGL_FOR_EACH_H
  3. #include "igl_inline.h"
  4. #include <Eigen/Core>
  5. #include <Eigen/Sparse>
  6. namespace igl
  7. {
  8. // FOR_EACH Call a given function for each non-zero (i.e., explicit value
  9. // might actually be ==0) in a Sparse Matrix A _in order (of storage)_. This is
  10. // useless unless func has _side-effects_.
  11. //
  12. // Inputs:
  13. // A m by n SparseMatrix
  14. // func function handle with prototype "compatible with" `void (Index i,
  15. // Index j, Scalar & v)`. Return values will be ignored.
  16. //
  17. // See also: std::for_each
  18. template <typename AType, typename Func>
  19. inline void for_each(
  20. const Eigen::SparseMatrix<AType> & A,
  21. const Func & func);
  22. template <typename DerivedA, typename Func>
  23. inline void for_each(
  24. const Eigen::DenseBase<DerivedA> & A,
  25. const Func & func);
  26. }
  27. // Implementation
  28. template <typename AType, typename Func>
  29. inline void igl::for_each(
  30. const Eigen::SparseMatrix<AType> & A,
  31. const Func & func)
  32. {
  33. // Can **not** use parallel for because this must be _in order_
  34. // Iterate over outside
  35. for(int k=0; k<A.outerSize(); ++k)
  36. {
  37. // Iterate over inside
  38. for(typename Eigen::SparseMatrix<AType>::InnerIterator it (A,k); it; ++it)
  39. {
  40. func(it.row(),it.col(),it.value());
  41. }
  42. }
  43. }
  44. template <typename DerivedA, typename Func>
  45. inline void igl::for_each(
  46. const Eigen::DenseBase<DerivedA> & A,
  47. const Func & func)
  48. {
  49. // Can **not** use parallel for because this must be _in order_
  50. if(A.IsRowMajor)
  51. {
  52. for(typename DerivedA::Index i = 0;i<A.rows();i++)
  53. {
  54. for(typename DerivedA::Index j = 0;j<A.cols();j++)
  55. {
  56. func(i,j,A(i,j));
  57. }
  58. }
  59. }else
  60. {
  61. for(typename DerivedA::Index j = 0;j<A.cols();j++)
  62. {
  63. for(typename DerivedA::Index i = 0;i<A.rows();i++)
  64. {
  65. func(i,j,A(i,j));
  66. }
  67. }
  68. }
  69. }
  70. //#ifndef IGL_STATIC_LIBRARY
  71. //# include "for_each.cpp"
  72. //#endif
  73. #endif