Skip to content
Prev 4891 / 10988 Next

[Rcpp-devel] Sparse matrices with RcppArmadillo

Le 08/12/12 09:45, S?ren H?jsgaard a ?crit :
Doug might know better about the internals of Matrix types. This is just 
following the recipee from how these are handled in RcppEigen:

#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
using namespace Rcpp ;

// [[Rcpp::export]]
void convert(S4 mat){
     IntegerVector dims = mat.slot( "Dim" ) ;
     IntegerVector i = mat.slot( "i" ) ;
     IntegerVector p = mat.slot( "p" ) ;
     NumericVector x = mat.slot( "x" ) ;

     int nrow = dims[0], ncol = dims[1] ;
     arma::sp_mat res( nrow, ncol) ;
     for(int j = 0; j < ncol; ++j) {
         for (int k = p[j]; k < p[j + 1]; ++k) res( i[k], j ) = x[k];
     }
     std::cout << res << std::endl ;

}


/*** R
     require(Matrix)
     i <- c(1,3:8); j <- c(2,9,6:10); x <- 7 * (1:7)
     ( A <- sparseMatrix(i, j, x = x) )

     convert(A)
***/

I don't think there is a better way to fill multiple values ina SpMat, 
maybe Conrad has insights.

Romain