Rcpp: Syntactic sugar for * produces unexpected results when dealing with NumericMatrix

前端 未结 2 879
抹茶落季
抹茶落季 2021-01-20 16:09

A recently asked question has lead me to believe the syntactic sugar for * by Rcpp does not work as intended. In the linked question, the user is t

相关标签:
2条回答
  • 2021-01-20 16:17

    As I stated in previous answers, when I need to do actual math on matrices, I use Armadillo objects:

    R> cppFunction('arma::mat scott(arma::mat x, double z) { 
    +                 return(x*z); }', 
    +              depends="RcppArmadillo")
    R> scott(matrix(1:4,2), 2)
         [,1] [,2]
    [1,]    2    6
    [2,]    4    8
    R> 
    

    Sugar operations are nice, but not complete. We will certainly take patches, though.

    And as we said a few times before: rcpp-devel is the proper support channel.

    Edit (Oct 2016 or 2 1/2 years later): Searching for something else just got me back here. In the Rcpp 0.12.* series, some work when into operations between matrix and vector so the basic 'matrix times scalar' now works as you'd expect:

    R> cppFunction("NumericMatrix testmat(NumericMatrix m, double multme) { 
    +               NumericMatrix n = m * multme; 
    +               return n; }") 
    R> testmat(matrix(1:4,2), 1)
         [,1] [,2]
    [1,]    1    3
    [2,]    2    4
    R> testmat(matrix(1:4,2), 3)
         [,1] [,2]
    [1,]    3    9
    [2,]    6   12
    R> 
    

    I'd probably still use RcppArmadillo for math on matrices though.

    0 讨论(0)
  • 2021-01-20 16:41

    This is an unfortunate consequence of a bad design decision, namely making Rcpp matrices derive from Rcpp vectors.

    I'm likely to revert this decision in Rcpp implementations I now maintain: Rcpp11 and Rcpp98. I don't think anymore that there any benefit of having Matrix derive from Vector and it gets in the way of CRTP that is used at the end of this file.

    0 讨论(0)
提交回复
热议问题