sum.h 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. // Implementation
  27. template <typename T>
  28. inline void igl::sum(
  29. const Eigen::SparseMatrix<T>& X,
  30. const int dim,
  31. Eigen::SparseVector<T>& S)
  32. {
  33. // dim must be 2 or 1
  34. assert(dim == 1 || dim == 2);
  35. // Get size of input
  36. int m = X.rows();
  37. int n = X.cols();
  38. // resize output
  39. if(dim==1)
  40. {
  41. S = Eigen::SparseVector<T>(n);
  42. }else
  43. {
  44. S = Eigen::SparseVector<T>(m);
  45. }
  46. // Iterate over outside
  47. for(int k=0; k<X.outerSize(); ++k)
  48. {
  49. // Iterate over inside
  50. for(typename Eigen::SparseMatrix<T>::InnerIterator it (X,k); it; ++it)
  51. {
  52. if(dim == 1)
  53. {
  54. S.coeffRef(it.col()) += it.value();
  55. }else
  56. {
  57. S.coeffRef(it.row()) += it.value();
  58. }
  59. }
  60. }
  61. }
  62. #endif