如何使用迭代器和犰狳稀疏矩阵来使用写访问?

How to use write access using iterators and armadillo sparse matrices?

我必须根据条件将一个稀疏矩阵中的某些列替换为另一个稀疏矩阵中的列,该矩阵具有相同的非零元素,只是值不同。

我正在努力使用 Armadillo 中的迭代器进行写访问。文档说使用 sp_mat::col_iterator 提供 read/write 访问权限,但是,当我尝试写入值 *it = B.col(...) 时,我收到一条错误消息 error: no match for ‘operator=’ (operand types are ‘arma::SpValProxy<arma::SpMat<double> >’ and ‘arma::SpSubview_col<double>’)。我有语法错误还是我对“写入权限”的概念理解有误?

  arma::sp_mat A = arma::sprandu(100, 100, 0.01);
  arma::sp_mat B(A);
  B *= 2;
  arma::vec condition = arma::randi<arma::vec>(100, arma::distr_param(0, 1));
  
  arma::sp_mat::col_iterator it = A.begin();
  arma::sp_mat::col_iterator it_end = A.end();
  for(; it != it_end; ++it){
    if (condition(it.col())==1){
      *it = B.col(it.col());
    }
  }

我目前的解决方案是编写一个函数,从各个矩阵中收集索引和值,然后使用批处理初始化,类似于 。尽管如此,我仍然想了解 read/write 访问和迭代器。

查看(总体上非常好)Armadillo documentation,我认为您遇到了设计问题。引用

Caveats:

  • to modify the non-zero elements in a safer manner, use .transform() or .for_each() instead of iterators;
  • writing a zero value into a sparse matrix through an iterator will invalidate all current iterators associated with the sparse matrix row iterators for sparse matrices are only useful with Armadillo 8.500 and later versions; in earlier versions they are inefficient