由于我不是C ++(或Rcpp)专家,所以我想知道下面是否还有其他/更好的方法来编写此小函数,该函数使用2个for循环基于其他2个矩阵的值填充矩阵
以下是一些示例数据:
library(Rcpp)
sizem <- 50000
n <- 500
k <- 5
d <- matrix(nrow = n, ncol = k, 0)
x <- matrix(nrow = n, ncol = sizem, runif(sizem*n, 0, 500))
rownames(x) <- paste0("p-",1:n)
v <- matrix(nrow = k, ncol = sizem, sample(0:300, size = sizem*k, T))
该函数当前如下所示:
cppFunction("
NumericMatrix compdistc(NumericMatrix d, NumericMatrix x, NumericMatrix v, int k, int n) {
NumericMatrix out = clone(d);
int i,j;
for (j=0; j < k; ++j) {
for (i=0; i < n; ++i) {
out(i,j) = sum(pow((x(i,_) - v(j,_)), 2));
}
}
return(out);
}
")
out <- compdistc(d, x, v, k, n)
这是我当前的基准:
mc <- microbenchmark(times = 10,
out = compdistc(d, x, v, k, n)
); mc
Unit: seconds expr min lq mean median uq max neval out 2.123477 2.135013 2.174556 2.148467 2.204108 2.354089 10