我想學習和使用稀疏線性代數例程Rcpp和RcppArmadillo。下面大SpMat對象與RcppArmadillo
代碼是這裏的例子改編:http://gallery.rcpp.org/articles/armadillo-sparse-matrix/
code <- '
S4 matx(x);
IntegerVector Xd = matx.slot("Dim");
IntegerVector Xi = matx.slot("i");
IntegerVector Xp = matx.slot("p");
NumericVector Xx = matx.slot("x");
arma::sp_mat Xsp(Xd[0], Xd[1]);
// create space for values, and copy
arma::access::rw(Xsp.values) = arma::memory::acquire_chunked<double>(Xx.size() + 1);
arma::arrayops::copy(arma::access::rwp(Xsp.values),
Xx.begin(),
Xx.size() + 1);
// create space for row_indices, and copy -- so far in a lame loop
arma::access::rw(Xsp.row_indices) = arma::memory::acquire_chunked<arma::uword>(Xx.size() + 1);
for (int j=0; j<Xi.size(); j++)
arma::access::rwp(Xsp.row_indices)[j] = Xi[j];
// create space for col_ptrs, and copy -- so far in a lame loop
arma::access::rw(Xsp.col_ptrs) = arma::memory::acquire_chunked<arma::uword>(Xp.size() + 1);
for (int j=0; j<Xp.size(); j++)
arma::access::rwp(Xsp.col_ptrs)[j] = Xp[j];
// important: set the sentinel as well
arma::access::rwp(Xsp.col_ptrs)[Xp.size()+1] = std::numeric_limits<arma::uword>::max();
// set the number of non-zero elements
arma::access::rw(Xsp.n_nonzero) = Xx.size();
Rcout << "SpMat Xsp:\\n" << arma::dot(Xsp,Xsp) << std::endl;
'
norm2 <- cxxfunction(signature(x="Matrix"),
code,plugin="RcppArmadillo")
當我使用1E4的載體,東西很好地工作:
> p <- 10000
> X <- Matrix(rnorm(p),sparse=TRUE)
> norm2(X)
SpMat Xsp:
9997.14
NULL
然而,當我使用長度1E5的矢量,錯誤產生
> p <- 100000
> X <- Matrix(rnorm(p),sparse=TRUE)
> norm2(X)
error: SpMat::init(): requested size is too large
Error:
>
我似乎無法弄清楚我是什麼做錯了。 任何指針,將不勝感激。
==============更多信息==============
這個問題似乎是與具有尺寸> = 2^16 = 65536
以下工作:
> m <- 1000
> n <- 65535
> nnz <- 10000
> iind <- sample.int(m,nnz,replace=TRUE)
> jind <- sample.int(n,nnz,replace=TRUE)
> xval <- rnorm(nnz)
> X <- sparseMatrix(i=iind,j=jind,x=xval,dims=c(m,n))
> norm2(X)
SpMat Xsp:
10029.8
NULL
繼不起作用:
> m <- 1000
> n <- 65536
> nnz <- 10000
> iind <- sample.int(m,nnz,replace=TRUE)
> jind <- sample.int(n,nnz,replace=TRUE)
> xval <- rnorm(nnz)
> X <- sparseMatrix(i=iind,j=jind,x=xval,dims=c(m,n))
> norm2(X)
error: SpMat::init(): requested size is too large
Error:
>
爲什麼會是這種情況?
這是一隻犰狳蟲。我相應地編輯了我的答案。 – 2013-04-30 15:56:35