Reputation: 87
there is something unclear by using for loop with Rcpp function. here is a simple example that should help:
This is my cpp code in file test_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 ;
}
Then from the R code why res1
and res2
are different when used in a 'useless' for loop and the same without for loop? I guess there is a segfault stuff, but I did not get it!
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!
Upvotes: 0
Views: 80
Reputation: 26823
The error lies here:
// Matrix of mat_size rows & mat_size columns (filled with 0)
arma::mat matrix_out(mat_size, mat_size) ;
The documentation says:
mat(n_rows, n_cols) (memory is not initialised)
mat(n_rows, n_cols, fill_type) (memory is initialised)
So if you change your code to
// Matrix of mat_size rows & mat_size columns (filled with 0)
arma::mat matrix_out(mat_size, mat_size, arma::fill::zeros) ;
The comment is actually right and the problem goes away.
Upvotes: 4