gpt4 book ai didi

c++ - Rcpparmadillo C++ 创建 bool vector

转载 作者:搜寻专家 更新时间:2023-10-31 00:59:57 24 4
gpt4 key购买 nike

我正在尝试使用 Rcpparmadillo 将 bool vector 作为参数传递给函数。一个愚蠢的例子看起来像这样:

// [[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>建议使用 type 但对我不起作用。我试过了 uvecstd::vector<bool>也一样,但也不起作用。使用 Rcpparmadillo 将逻辑 vector 作为参数传递的最佳方法是什么? ?

最佳答案

您需要 Armadillo 的 uvec —— 它没有 bool 类型。这是您的代码的重新格式化版本* 使用 uvec* 直接索引 vector

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

如果我们sourceCpp()这个,它会在底部为我们运行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>

关于c++ - Rcpparmadillo C++ 创建 bool vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32309915/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com