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

问题描述

我必须用另一个稀疏矩阵中的列替换稀疏矩阵中的一些列,这些列具有相同的非零元素,只是基于条件不同的值。

我正在努力在 Armadillo 中使用迭代器进行写访问。文档说使用 sp_mat::col_iterator 提供读/写访问,但是,当我尝试写入值 *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());
    }
  }

我目前的解决方案是编写一个函数,从相应的矩阵中收集索引和值,然后使用批处理初始化,类似于 Access and modify the non zero elements of sparse matrix of class arma::sp_mat using Rcpp code。尽管如此,我还是想了解读/写访问和迭代器。

解决方法

看看(通常非常出色)Armadillo documentation,我认为您遇到了设计问题。引用

注意事项:

  • 要以更安全的方式修改非零元素,请使用 .transform() 或 .for_each() 而不是迭代器;
  • 通过迭代器将零值写入稀疏矩阵将使与稀疏矩阵关联的所有当前迭代器失效 稀疏矩阵的行迭代器仅适用于 Armadillo 8.500 及更高版本;在早期版本中,它们效率低下

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...