首先,我是一個新手用戶,所以忘記了我的一般無知。我正在尋找一種更快的替代方法來運行R中的%*%運算符。儘管較舊的帖子提示使用RcppArmadillo,但我已經嘗試了2個小時來使RcppArmadillo無法成功運行。我總是遇到產生'意外...'錯誤的詞彙問題。我發現在RCPP下面的功能,我可以讓工作:Rcpp中的矩陣乘法
library(Rcpp)
func <- '
NumericMatrix mmult(NumericMatrix m , NumericMatrix v, bool byrow=true)
{
if(! m.nrow() == v.nrow()) stop("Non-conformable arrays") ;
if(! m.ncol() == v.ncol()) stop("Non-conformable arrays") ;
NumericMatrix out(m) ;
for (int i = 0; i < m.nrow(); i++)
{
for (int j = 0; j < m.ncol(); j++)
{
out(i,j)=m(i,j) * v(i,j) ;
}
}
return out ;
}
'
這個功能,但是,進行逐元素乘法和不表現爲%*%。有沒有簡單的方法來修改上面的代碼來實現預期的結果?
編輯:
我已經想出了使用RcppEigen似乎擊敗%*%功能:
etest <- cxxfunction(signature(tm="NumericMatrix",
tm2="NumericMatrix"),
plugin="RcppEigen",
body="
NumericMatrix tm22(tm2);
NumericMatrix tmm(tm);
const Eigen::Map<Eigen::MatrixXd> ttm(as<Eigen::Map<Eigen::MatrixXd> >(tmm));
const Eigen::Map<Eigen::MatrixXd> ttm2(as<Eigen::Map<Eigen::MatrixXd> >(tm22));
Eigen::MatrixXd prod = ttm*ttm2;
return(wrap(prod));
")
set.seed(123)
M1 <- matrix(sample(1e3),ncol=50)
M2 <- matrix(sample(1e3),nrow=50)
identical(etest(M1,M2), M1 %*% M2)
[1] TRUE
res <- microbenchmark(
+ etest(M1,M2),
+ M1 %*% M2,
+ times=10000L)
res
Unit: microseconds
expr min lq mean median uq max neval
etest(M1, M2) 5.709 6.61 7.414607 6.611 7.211 49.879 10000
M1 %*% M2 11.718 12.32 13.505272 12.621 13.221 58.592 10000
的評論是部分不正確在RcppEigen _不_依靠系統複製Eigen,但帶來自己的,類似於其他R包。 –
啊,謝謝你的澄清,@DirkEddelbuettel。很高興知道。我認爲這是一個包裝。 – RHertel