以特定方式生成随机矩阵(Rcpp)

问题描述 投票:0回答:1

我想使用 Rcpp 生成随机矩阵。通过以下方式;

#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;
}

这段代码运行良好,没有什么随机的。现在我通过以下方式融入随机性

// [[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;
}

这会产生错误;

reference to overloded function could not be resolved; did you mean to call it?

我知道我犯了一个基本错误,但我无法察觉。任何形式的帮助都是值得的。

r rcpp
1个回答
0
投票

您向

R::rnorm()
提供了三个参数,而它只需要两个参数。 (不要与
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
> 
© www.soinside.com 2019 - 2024. All rights reserved.