sum.h 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #ifndef IGL_SUM_H
  2. #define IGL_SUM_H
  3. #include <Eigen/Sparse>
  4. namespace igl
  5. {
  6. // Note: If your looking for dense matrix matlab like sum for eigen matrics
  7. // just use:
  8. // M.colwise().sum() or M.rowwise().sum()
  9. //
  10. // Sum the columns or rows of a sparse matrix
  11. // Templates:
  12. // T should be a eigen sparse matrix primitive type like int or double
  13. // Inputs:
  14. // X m by n sparse matrix
  15. // dim dimension along which to sum (1 or 2)
  16. // Output:
  17. // S n-long sparse vector (if dim == 1)
  18. // or
  19. // S m-long sparse vector (if dim == 2)
  20. template <typename T>
  21. inline void sum(
  22. const Eigen::SparseMatrix<T>& X,
  23. const int dim,
  24. Eigen::SparseVector<T>& S);
  25. }
  26. template <typename T>
  27. inline void igl::sum(
  28. const Eigen::SparseMatrix<T>& X,
  29. const int dim,
  30. Eigen::SparseVector<T>& S)
  31. {
  32. // dim must be 2 or 1
  33. assert(dim == 1 || dim == 2);
  34. // Get size of input
  35. int m = X.rows();
  36. int n = X.cols();
  37. // resize output
  38. if(dim==1)
  39. {
  40. S = Eigen::SparseVector<T>(n);
  41. }else
  42. {
  43. S = Eigen::SparseVector<T>(m);
  44. }
  45. // Iterate over outside
  46. for(int k=0; k<X.outerSize(); ++k)
  47. {
  48. // Iterate over inside
  49. for(typename Eigen::SparseMatrix<T>::InnerIterator it (X,k); it; ++it)
  50. {
  51. if(dim == 1)
  52. {
  53. S.coeffRef(it.col()) += it.value();
  54. }else
  55. {
  56. S.coeffRef(it.row()) += it.value();
  57. }
  58. }
  59. }
  60. }
  61. #endif