我正在使用RcppArmadillo访问和更新Armadillo中类arma:sp_mat
的稀疏矩阵的非零元素。例如,在Matrix R包中,如果B
是类dgCMatrix
的稀疏矩阵,则可以通过执行以下操作来访问和修改其非零元素:
B@x[] = xx
其中xx
是包含实际非零元素的新向量。有人可以帮我用犰狳代码做同样的事情吗?
答案 0 :(得分:2)
不幸的是,没有一个很好的访问者可以返回sp_mat
中条目的位置。
要获取此信息,我们首先计算列表中的元素数量,创建位置umat
,然后构建新的sp_mat
using a batch constructor as recommended by the API docs。
#include <RcppArmadillo.h>
using namespace Rcpp;
// [[Rcpp::depends(RcppArmadillo)]]
// Obtains a list of coordinates from the sparse matrix by using iterators
// First calculates total number of points and, then, obtains list.
// [[Rcpp::export]]
arma::umat get_locations(arma::sp_mat& B)
{
// Make const iterator
arma::sp_mat::const_iterator start = B.begin();
arma::sp_mat::const_iterator end = B.end();
// Calculate number of points
int n = std::distance(start, end);
// Kill process if no values are found (very sparse matrix)
if (n <= 0) { Rcpp::stop("No values found!"); }
// Build a location storage matrix
arma::umat locs(2, n);
// Create a vector to store each row information in. (Row, Col)
arma::uvec temp(2);
// Start collecting locations
arma::sp_mat::const_iterator it = start;
for(int i = 0; i < n; ++i)
{
temp(0) = it.row();
temp(1) = it.col();
locs.col(i) = temp;
++it; // increment
}
return locs;
}
// Updates the sparse matrix by constructing a new one
// [[Rcpp::export]]
arma::sp_mat update_sp_matrix(arma::sp_mat& B, arma::vec values)
{
// Get all the locatoins
arma::umat locs = get_locations(B);
// Make sure we have the correct number
if (locs.n_rows != values.n_elem) {
Rcpp::stop("Length mismatch between locations and supplied values!");
}
// The documentation recommends using batch constructor to rebuild matrix
B = arma::sp_mat(locs, values, B.n_rows, B.n_cols);
return B;
}
// Generates a sparse matrix interally to test with
// Dimensions are 10 x 10 with only 2 points filled in.
arma::sp_mat make_test_sp()
{
// creates a matrix C++98 style
arma::umat locs;
locs << 4 << 7 << arma::endr
<< 6 << 7 << arma::endr;
// creates a vector C++98 style
arma::vec vals;
vals << 4.5 << 8.2 << arma::endr;
arma::sp_mat B(locs, vals, 10, 10);
return B;
}
// Main runner calls the built in test generation function.
// [[Rcpp::export]]
arma::sp_mat test_me()
{
arma::sp_mat B = make_test_sp();
arma::vec temp = arma::ones<arma::vec>(2);
return update_sp_matrix(B, temp);
}
更改了get_location()
代码,以反映
sp_mat
结构
2 x N
而不是
N x 2
感谢@ EricH的评论