I am using armadillo and R through RcppArmadillo.
I have a sparse matrix and a row number as input. I would like to search the corresponding row of the matrix and return the location of the nonzeros.
So far my function looks like
// [[Rcpp::export]]
arma::uvec findAdjacentStates(arma::sp_mat adjacency, int row) {
arma::uvec out(adjacency.n_cols);
arma::SpSubview<double>::const_iterator start = adjacency.row(row).begin();
arma::SpSubview<double>::const_iterator end = adjacency.row(row).end();
for(arma::SpSubview<double>::const_iterator it = start; it != end; ++it)
{
Rcout << "location: " << it.row() << "," << it.col() << " ";
Rcout << "value: " << (*it) << std::endl;
}
return out;
}
which is based on a previous SO answer.
The function crashes R.
require(Matrix)
x = rsparsematrix(10, 10, .2)
x = x > 1
x = as(x, "dgCMatrix")
findAdjacentStates(x, 1)
One thing that is not clear to me is how to iterate on a row vector specifically; the previous SO answer was for iterating on a sparse matrix.
Update: according to valgrind the problem is in operator++ (SpSubview_iterators_meat.hpp:319), so it seems this is not the correct way to iterate on a sparse row vector