#ifndef IGL_SLICE_H #define IGL_SLICE_H #define EIGEN_YES_I_KNOW_SPARSE_MODULE_IS_NOT_STABLE_YET #include namespace igl { // Act like the matlab X(row_indices,col_indices) operator // // Inputs: // X m by n matrix // R list of row indices // C list of column indices // Output: // Y #R by #C matrix template inline void slice( const Eigen::SparseMatrix& X, const Eigen::Matrix & R, const Eigen::Matrix & C, Eigen::SparseMatrix& Y); template inline void slice( const Eigen::Matrix & X, const Eigen::Matrix & R, const Eigen::Matrix & C, Eigen::Matrix & Y); template inline void slice( const Eigen::Matrix & X, const Eigen::Matrix & R, Eigen::Matrix & Y); } // Implementation #include template inline void igl::slice( const Eigen::SparseMatrix& X, const Eigen::Matrix & R, const Eigen::Matrix & C, Eigen::SparseMatrix& Y) { int xm = X.rows(); int xn = X.cols(); int ym = R.size(); int yn = C.size(); // special case when R or C is empty if(ym == 0 || yn == 0) { Y.resize(ym,yn); return; } assert(R.minCoeff() >= 0); assert(R.maxCoeff() < xm); assert(C.minCoeff() >= 0); assert(C.maxCoeff() < xn); // Build reindexing maps for columns and rows, -1 means not in map std::vector > RI; RI.resize(xm); for(int i = 0;i > CI; CI.resize(xn); // initialize to -1 for(int i = 0;i dyn_Y(ym,yn); // Take a guess at the number of nonzeros (this assumes uniform distribution // not banded or heavily diagonal) dyn_Y.reserve((X.nonZeros()/(X.rows()*X.cols())) * (ym*yn)); // Iterate over outside for(int k=0; k::InnerIterator it (X,k); it; ++it) { std::vector::iterator rit, cit; for(rit = RI[it.row()].begin();rit != RI[it.row()].end(); rit++) { for(cit = CI[it.col()].begin();cit != CI[it.col()].end(); cit++) { dyn_Y.coeffRef(*rit,*cit) = it.value(); } } } } Y = Eigen::SparseMatrix(dyn_Y); } template inline void igl::slice( const Eigen::Matrix & X, const Eigen::Matrix & R, const Eigen::Matrix & C, Eigen::Matrix & Y) { int xm = X.rows(); int xn = X.cols(); int ym = R.size(); int yn = C.size(); // special case when R or C is empty if(ym == 0 || yn == 0) { Y.resize(ym,yn); return; } assert(R.minCoeff() >= 0); assert(R.maxCoeff() < xm); assert(C.minCoeff() >= 0); assert(C.maxCoeff() < xn); // Resize output Y.resize(ym,yn); // loop over output rows, then columns for(int i = 0;i inline void igl::slice( const Eigen::Matrix & X, const Eigen::Matrix & R, Eigen::Matrix & Y) { // phony column indices Eigen::Matrix C; C.resize(1); C(0) = 0; return igl::slice(X,R,C,Y); } #endif