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

落花浮王杯 提交于 2019-12-02 00:13:40

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.

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!