sum.h 1.4 KB

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