r - 将列向量乘以 RcppArmadillo 中的数值标量

标签 r matrix rcpp armadillo

我在编译这个简单的 c++ 时遇到了一些麻烦代码使用 RcppRcppArmadillo包裹。以下面的简单示例将矩阵的每一列乘以数值标量:

code <- 'arma::mat out = Rcpp::as<arma::mat>(m);
for(int i = 0; i < out.n_cols; ++i){
  out.col(i) *= v;
}
return Rcpp::wrap( out );'

尝试使用...
require( RcppArmadillo )
armMult <- cxxfunction( signature( m = "numeric" , v = "numeric" ),
                        code , plugin = "RcppArmadillo" )

结果在编译错误....
#error: no match for 'operator*=' in 'arma::Mat<eT>::col(arma::uword) [with eT = double, arma::uword = unsigned int](((unsigned int)i)) *= v'

但是,如果我们交换 numeric变量 v2.0如下....
code <- 'arma::mat out = Rcpp::as<arma::mat>(m);
for(int i = 0; i < out.n_cols; ++i){
  out.col(i) *= 2.0; //Notice we use 2.0 instead of a variable
}
return Rcpp::wrap( out );'

它编译得很好......
armMult <- cxxfunction( signature(m="numeric"),
                        code,plugin="RcppArmadillo")

然后我们可以做...
m <- matrix( 1:4 , 2 , 2 )

armMult( m )
     [,1] [,2]
[1,]    2    6
[2,]    4    8

我在这里错过了什么?我怎样才能用一个简单的数字标量来完成这项工作。我希望能够传递一个标量,如...
armMult( m , 2.0 )

并返回与上面相同的结果。

最佳答案

如果要乘以矩阵的每一列 A 通过向量的对应元素 x 然后试试这个:

Rcpp:::cppFunction(
    "arma::mat fun(arma::mat A, arma::rowvec x) 
    { 
        A.each_row() %= x;
        return A;
    }", depends = "RcppArmadillo"
)

fun(matrix(rep(1, 6), 3, 2), c(5, 1))

     [,1] [,2]
[1,]    5    1
[2,]    5    1
[3,]    5    1

关于r - 将列向量乘以 RcppArmadillo 中的数值标量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18361570/

相关文章:

python - 关于带有 n 排列的 Minhash 实现的建议

具有 Rcpp::Function 成员的 C++ 类

r - AWS dynamodb 对 "R"编程语言的支持

r - 在分组数据上使用工具提示时,ggvis 中的值消失

R sf - 如何平移多边形?

python - 如何将矩阵顺时针旋转 90 度?

C++ 矩阵类

r - 更新到 macOS Catalina 后无法使用 C++ 代码编译 R 包

c++ - 对工作程序中自定义函数的 undefined reference (C++ 和 RcppParallel)

r - 无法让 alpha 与 ggplot2::geom_sf 在 sf linestring 对象上一起使用