Multiplying a column vector by a numeric scalar in RcppArmadillo

僤鯓⒐⒋嵵緔 提交于 2019-12-04 15:59:03

If you want to multiply each column of a matrix A by the corresponding element of a vector x then try this:

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

Whenever I scratch my head over issues like this, I start by reducing the problem. Try a C++ three-liner just using Armadillo headers. Make it work, then move it over to RcppArmadillo.

Edit: One can do better than your answer as you don't need to multiply each column individually (though one can). Anyway, this just shows off Rcpp Attributes:

> cppFunction("arma::mat simon(arma::mat m, double v) { return m * v;}", 
+             depends="RcppArmadillo")
> simon(matrix(1:4,2,2), 3)
     [,1] [,2]
[1,]    3    9
[2,]    6   12
> 

Thanks to a comment by @DirkEddelbuettel it was simply because I had not defined v...

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

armMult <- cxxfunction( signature( m = "numeric" , v = "numeric" ),
                        code , plugin = "RcppArmadillo" )

armMult( m , 2.0 )
     [,1] [,2]
[1,]    2    6
[2,]    4    8
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!