[英]Rcpp: one function works on NumericVector, the other needs to treat it as scalar
我有兩個用Rcpp編寫的函數。
第一個函數f
以NumericVector作為輸入,並返回NumericVector作為輸出。 但是通常, f
被視為標量函數。 當我從R調用它時,這沒關系,因為R無論如何都會將任何標量都視為向量,因此我不必理會它。 我都可以將f
用作標量或向量函數,例如f(1)
和f(c(1,2,3,4)
都可以工作。
f
時,是否會有一些不必要的開銷? 第二個函數g
需要將f
純粹用作標量函數。 這引起了一個問題,因為在定義g
...時我需要從Rcpp調用f
...。現在我不能通過為某些double x調用f(x
)將其用作標量函數。
我試圖從g
的定義中做這樣的事情:
NumericVector x = NumericVector::create(value); //create vector of length 1
f(x) //use f(x) as scalar
但是對代碼進行計時花了很長的時間(因為函數g
需要多次執行上述操作)。
f
視為標量函數? 我當前的解決方案是按照Queston 1中的要求進行操作:創建另一個標量的f
函數,然后從g
調用THAT,所以在g
內部我們只是說
alternative_f(x) //use alternative f as scalar
您可以將標量代碼分解為一個單獨的(內聯)函數,然后從f
(帶有std::transform
)和g
(帶有附加邏輯)中調用它。 簡化示例:
#include <Rcpp.h>
inline double f_impl (double x) {
return x * 2;
}
// [[Rcpp::export]]
double g (double x) {
return f_impl(x) + 2;
}
// [[Rcpp::export]]
Rcpp::NumericVector f (Rcpp::NumericVector x) {
Rcpp::NumericVector y(Rcpp::no_init(x.length()));
std::transform(x.begin(), x.end(), y.begin(), f_impl);
return y;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.