【发布时间】:2018-04-04 14:49:23
【问题描述】:
此问题与this 和this 有关。这里的不同之处在于,我传递的不是NumericVector 或NumericMatrix 之类的Rcpp 类型,而是arma::sp_mat。
有没有办法将sp_mat 传递给 C++,修改它的值,并让更改显示在 R 中的原始对象中?
这可以通过NumericMatrix 来完成,例如:
cppFunction("void frob(NumericMatrix& x)
{
for(NumericMatrix::iterator it = x.begin(); it != x.end(); ++it)
{
if(*it != 0) *it = *it + 5;
}
}")
M <- Matrix(0, 5, 1, sparse=TRUE)
M[1] <- 1.2345
m <- as.matrix(M)
frob(m)
m
#[,1]
#[1,] 6.2345
#[2,] 0.0000
#[3,] 0.0000
#[4,] 0.0000
#[5,] 0.0000
同样的技术适用于arma::mat 密集矩阵。但是对于稀疏矩阵,它不起作用:
cppFunction("void frob2(arma::sp_mat& x)
{
for(arma::sp_mat::iterator it = x.begin(); it != x.end(); ++it)
{
*it = *it + 5;
}
}", depends="RcppArmadillo")
frob2(M)
M
#5 x 1 sparse Matrix of class "dgCMatrix"
#[1,] 1.2345
#[2,] .
#[3,] .
#[4,] .
#[5,] .
【问题讨论】:
-
嗯,这可能是去年夏天对稀疏进口商所做的工作的回归。
-
@coatless 很有趣,所以这不是预期的行为吗?有没有办法修改矩阵而不进行不必要的复制?
-
不确定我们曾经有过引用语义。毕竟,稀疏矩阵没有原生类型,所以需要在某个地方复制一些东西......
标签: r sparse-matrix rcpp armadillo