Looping nonzero elements of a sparse matrix uBlas

I have the following sparse matrix containing O(N) elements

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

I could write a double iteration loop to iterate over all the records in O(N^2) time, as shown below, but it will 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 iterate over only non-zero entries in O(N) time? For each nonzero element, I would like to access its value and the indices i,j .

+7
c ++ boost sparse-matrix ublas
source share
1 answer

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

In your case, it will 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; } } 
+14
source share

All Articles