Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating random matrix with a specific way (Rcpp)

Tags:

r

rcpp

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.

like image 272
ann Avatar asked Oct 16 '25 21:10

ann


1 Answers

You are supplying three arguments to R::rnorm() which only takes two. (Don't confuse it with Rcpp::rnorm() !!)

Code

#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))
*/

Output

> 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
> 
like image 170
Dirk Eddelbuettel Avatar answered Oct 19 '25 11:10

Dirk Eddelbuettel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!