1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768 |
- #ifndef IGL_SUM_H
- #define IGL_SUM_H
- #include <Eigen/Sparse>
- namespace igl
- {
- // Note: If your looking for dense matrix matlab like sum for eigen matrics
- // just use:
- // M.colwise().sum() or M.rowwise().sum()
- //
- // Sum the columns or rows of a sparse matrix
- // Templates:
- // T should be a eigen sparse matrix primitive type like int or double
- // Inputs:
- // X m by n sparse matrix
- // dim dimension along which to sum (1 or 2)
- // Output:
- // S n-long sparse vector (if dim == 1)
- // or
- // S m-long sparse vector (if dim == 2)
- template <typename T>
- inline void sum(
- const Eigen::SparseMatrix<T>& X,
- const int dim,
- Eigen::SparseVector<T>& S);
- }
- // Implementation
- template <typename T>
- inline void igl::sum(
- const Eigen::SparseMatrix<T>& X,
- const int dim,
- Eigen::SparseVector<T>& S)
- {
- // dim must be 2 or 1
- assert(dim == 1 || dim == 2);
- // Get size of input
- int m = X.rows();
- int n = X.cols();
- // resize output
- if(dim==1)
- {
- S = Eigen::SparseVector<T>(n);
- }else
- {
- S = Eigen::SparseVector<T>(m);
- }
- // Iterate over outside
- for(int k=0; k<X.outerSize(); ++k)
- {
- // Iterate over inside
- for(typename Eigen::SparseMatrix<T>::InnerIterator it (X,k); it; ++it)
- {
- if(dim == 1)
- {
- S.coeffRef(it.col()) += it.value();
- }else
- {
- S.coeffRef(it.row()) += it.value();
- }
- }
- }
- }
- #endif
|