[Rcpp-devel] Sparse matrices with RcppArmadillo

Romain Francois romain at r-enthusiasts.com
Sat Dec 8 15:03:58 CET 2012


Le 08/12/12 09:45, Søren Højsgaard a écrit :
> Dear all,
>
> I want to use a matrix (of type "dgCMatrix" from the Matrix package) in RcppArmadillo, so I do:
>
> library(inline)
> src <- '
> using namespace arma;
> using namespace Rcpp;
> SpMat<double> X = as<SpMat<double> >(XX_);
> '
> foo <- cxxfunction(signature(XX_=""), body=src, plugin="RcppArmadillo")
>
> - but this fails. It seems to me (browsing the web) that SpMat are supported, but I might be wrong here. I have no indication that dgCMatrix matrices can be "converted" to SpMat's. I know that I can work with dgCMatrix matrices with RcppEigen, but what I need is to extract submatrices and that is very easy to do with RcppArmadillo.
>
> Any thoughts? Thanks in advance.
> Regards
> Søren

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

-- 
Romain Francois
Professional R Enthusiast
+33(0) 6 28 91 30 30

R Graph Gallery: http://gallery.r-enthusiasts.com

blog:            http://romainfrancois.blog.free.fr
|- http://bit.ly/RE6sYH : OOP with Rcpp modules
`- http://bit.ly/Thw7IK : Rcpp modules more flexible



More information about the Rcpp-devel mailing list