Reputation: 41
I want to generate random matrix using Rcpp. In a following way;
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericMatrix testFunction1(IntegerVector idx, NumericMatrix x){
NumericMatrix temp(idx.size(),idx.size());
for(R_len_t i=0; i< idx.size(); i++){
for(R_len_t j=0; j< idx.size(); j++){
temp(i,j) = x(idx[i],idx[j]);
}
}
return temp;
}
This code working nicely and there is nothing random. Now I incorporate randomness in the following way
// [[Rcpp::export]]
NumericMatrix testFunction1(IntegerVector idx, NumericMatrix x){
NumericMatrix temp(idx.size(),idx.size());
for(R_len_t i=0; i< idx.size(); i++){
for(R_len_t j=0; j< idx.size(); j++){
temp(i,j) = R::rnorm(1, mu = x(idx[i],idx[j]), sd = 1);
}
}
return temp;
}
This gives a error;
reference to overloded function could not be resolved; did you mean to call it?
I know I made a basic mistake, which I unable to detect. Any kind of help appreceable.
Upvotes: 4
Views: 54
Reputation: 368499
You are supplying three arguments to R::rnorm()
which only takes two. (Don't confuse it with Rcpp::rnorm()
!!)
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericMatrix testFunction1(IntegerVector idx, NumericMatrix x){
NumericMatrix temp(idx.size(),idx.size());
for(R_len_t i=0; i< idx.size(); i++){
for(R_len_t j=0; j< idx.size(); j++){
temp(i,j) = R::rnorm(x(idx[i],idx[j]), 1);
}
}
return temp;
}
/*** R
set.seed(42)
testFunction1(1:4, matrix(1:16, 4, 4))
*/
> Rcpp::sourceCpp("~/git/stackoverflow/77361114/answer.cpp")
> set.seed(42)
> testFunction1(1:4, matrix(1:16, 4, 4))
[,1] [,2] [,3] [,4]
[1,] 7.37096 9.4353 14.363128 0.632863
[2,] 7.40427 10.8939 16.511522 -0.094659
[3,] 10.01842 11.9373 17.304870 2.286645
[4,] 7.61114 12.7212 -0.133321 0.635950
>
Upvotes: 4