我试图用Rcpparmadillo将bool向量作为参数传递给函数。一个愚蠢的例子如下所示:
// [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadillo.h>
// [[Rcpp::export]]
arma::mat myfun(arma::mat A, arma::vec mybool)
{
int n = A.n_rows;
arma::vec B(n);
for(unsigned int i = 0; i < n; ++i)
{
if(mybool.row(i) && i < 10) // mybool.row(i) && throws the error
{
B.row(i) = arma::accu(A.row(i));
}
else
{
B.row(i) = pow(arma::accu(A.row(i)), 0.5);
}
}
return B;
}Here是建议的mat<unsigned char>类型,但对我不起作用。我也尝试过uvec和std::vector<bool>,但也不起作用。使用Rcpparmadillo将逻辑向量作为参数传递的最佳方法是什么
发布于 2015-08-31 11:29:33
你想要Armadillo的uvec --它没有bool类型。下面是代码的重新格式化版本,它*直接使用uvec *索引向量
// [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadillo.h>
// [[Rcpp::export]]
arma::mat myfun(arma::mat A, arma::uvec mybool) {
unsigned int n = A.n_rows;
arma::vec B(n);
for (unsigned int i=0; i<n; ++i) {
if (mybool[i] && i < 10) {
B[i] = arma::accu(A.row(i)) ;
} else {
B[i] = pow(arma::accu(A.row(i)), 0.5);
}
} //end loop
return B;
}
/*** R
A <- matrix(1:16,4,4)
mybool <- c(FALSE, TRUE, TRUE, FALSE)
myfun(A, mybool)
*/如果我们这样做,它会在底部为我们运行R:
R> sourceCpp("/tmp/ap13.cpp")
R> A <- matrix(1:16,4,4)
R> mybool <- c(FALSE, TRUE, TRUE, FALSE)
R> myfun(A, mybool)
[,1]
[1,] 5.29150
[2,] 32.00000
[3,] 36.00000
[4,] 6.32456
R> https://stackoverflow.com/questions/32309915
复制相似问题