通过将Rcpp函数与for循环一起使用,还不清楚。这是一个应该有用的简单示例:
这是我在文件test_cpp.cpp
中的cpp代码
#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::export]]
arma::mat test_Cpp(int n,
arma::vec my_vec,
Rcpp::List my_list,
int mat_size,
double lambda,
double beta) {
// Matrix of mat_size rows & mat_size columns (filled with 0)
arma::mat matrix_out(mat_size, mat_size) ;
for (int it = 0 ; it < n ; ++it) {
arma::mat temp_mat_flux_convol = my_list[it] ;
if (my_vec[it] != 0) {
matrix_out += lambda * my_vec[it] * beta * temp_mat_flux_convol ;
}
}
return matrix_out ;
}
然后从R代码中,为什么res1
和res2
在“无用”的for循环中使用时和在没有for循环中相同时为何不同?我猜有一个段错误的东西,但是我没有得到!
library(Rcpp)
library(RcppArmadillo)
sourceCpp(file = "src/test_cpp.cpp")
set.seed(123)
ls_rand = lapply(1:10, function(x) matrix(rnorm(9), ncol=3))
for(i in 1:1){
res1 <- test_Cpp(n = 10,
my_vec = 1:100,
my_list = ls_rand,
mat_size = 3,
lambda = 24,
beta = 0.4)
res2 <- test_Cpp(n = 10,
my_vec = 1:100,
my_list = ls_rand,
mat_size = 3,
lambda = 24,
beta = 0.4)
}
all.equal(res1, res2)
res1 ; res2 # here res2 is twice res1 !!!
## Without for loop
res1 <- test_Cpp(n = 10,
my_vec = 1:100,
my_list = ls_rand,
mat_size = 3,
lambda = 24,
beta = 0.4)
res2 <- test_Cpp(n = 10,
my_vec = 1:100,
my_list = ls_rand,
mat_size = 3,
lambda = 24,
beta = 0.4)
all.equal(res1, res2)
res1 ; res2 # here res1 and res2 are the same!
答案 0 :(得分:4)
错误在这里:
// Matrix of mat_size rows & mat_size columns (filled with 0)
arma::mat matrix_out(mat_size, mat_size) ;
mat(n_rows,n_cols)(内存未初始化)
mat(n_rows,n_cols,fill_type)(内存已初始化)
因此,如果您将代码更改为
// Matrix of mat_size rows & mat_size columns (filled with 0)
arma::mat matrix_out(mat_size, mat_size, arma::fill::zeros) ;
评论实际上是正确的,问题就消失了。