犰狳中的Rcpp Sugar命令 [英] Rcpp sugar commands in armadillo
问题描述
我正在尝试将Rcpp sugar的 ifelse()
命令与 arma :: vec
一起使用.代码失败并显示错误
I'm trying to use ifelse()
command of Rcpp sugar with arma::vec
. The code fails with error
'ifelse'
我找不到解决方案.下面是一个简单的示例代码(导致错误).
I could not find a solution. A simple example code (resulted with error) is below.
#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::export]]
arma::vec f(arma::vec x, arma::vec y) {
arma::vec res1 = Rcpp::ifelse(x < y, x, y);
arma::vec res = trans(res1)*y;
return res;
}
/*** R
f(c(1,2,3),c(3,2,1))
*/
推荐答案
使用Armadillo的高级构造函数您可以使 Rcpp :: NumericVector
和 arma :: vec
指向相同的内存位置.然后,可以通过使用该内存的正确前端对象来同时使用 Rcpp
函数和 arma
函数:
Using Armadillo's advanced constructors you can have Rcpp::NumericVector
and arma::vec
that refer to the same memory location. Then you can use both Rcpp
functions and arma
functions by using the correct front-end object for that piece of memory:
#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::export]]
arma::vec f(Rcpp::NumericVector xr, Rcpp::NumericVector yr) {
arma::vec x(xr.begin(), xr.size(), false, true);
arma::vec y(yr.begin(), yr.size(), false, true);
Rcpp::NumericVector res1r(xr.size());
arma::vec res1(res1r.begin(), res1r.size(), false, true);
res1r = Rcpp::ifelse(xr < yr, xr, yr);
arma::vec res = trans(res1)*y;
return res;
}
/*** R
f(c(1,2,3),c(3,2,1))
*/
我不是100%肯定它不会有任何不良副作用.
I am not 100% sure that this does not have any unwanted side-effects.
这篇关于犰狳中的Rcpp Sugar命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!