问题描述
我在使用Rcpp
和RcppArmadillo
软件包编译此简单的c++
代码时遇到了一些麻烦.以下面的简单示例为例,将矩阵的每一列乘以数字标量:
I am having some trouble compiling this simple c++
code using Rcpp
and the RcppArmadillo
package. Take the following simple example to multiply each column of a matrix by a numeric scalar:
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 );'
尝试使用...来编译它
Trying to compile this using...
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
变量v
换为2.0
,如下所示....
However, if we swap the numeric
variable v
for 2.0
as below....
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")
然后我们可以做...
And we can then do...
m <- matrix( 1:4 , 2 , 2 )
armMult( m )
[,1] [,2]
[1,] 2 6
[2,] 4 8
我在这里想念什么?如何使用简单的数字标量来实现此目的.我希望能够通过像...这样的标量.
What am I missing here? How can I make this work with a simple numeric scalar. I would like to be able to pass a scalar like...
armMult( m , 2.0 )
并返回与上面相同的结果.
And return the same result as above.
推荐答案
如果要将矩阵 A 的每一列乘以向量的相应元素 x 然后试试这个:
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
这篇关于在RcppArmadillo中将列向量乘以数字标量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!