Looping over the non-zero elements of a uBlas sparse matrix

蹲街弑〆低调 提交于 2019-11-29 20:34:19

问题


I have the following sparse matrix that contains O(N) elements

boost::numeric::ublas::compressed_matrix<int> adjacency (N, N);

I could write a brute force double loop to go over all the entries in O(N^2) time like below, but this is going to be too slow.

for(int i=0; i<N; ++i)
   for(int j=0; j<N; ++j)
       std::cout << adjacency(i,j) std::endl;

How can I loop over only the non-zero entries in O(N) time? For each non-zero element I would like to have access to its value, and the indexes i,j.


回答1:


You can find the answer in this FAQ: How to iterate over all non zero elements?

In your case it would be:

typedef boost::numeric::ublas::compressed_matrix<int>::iterator1 it1_t;
typedef boost::numeric::ublas::compressed_matrix<int>::iterator2 it2_t;

for (it1_t it1 = adjacency.begin1(); it1 != adjacency.end1(); it1++)
{
  for (it2_t it2 = it1.begin(); it2 != it1.end(); it2++)
  {
    std::cout << "(" << it2.index1() << "," << it2.index2() << ") = ";
    std::cout << *it2 << std::endl;
  }
}


来源:https://stackoverflow.com/questions/1795658/looping-over-the-non-zero-elements-of-a-ublas-sparse-matrix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!