Iterate through two sparse matrices

I am using extended sparse matrices containing bool and trying to write a comparison function to store them on a map. This is a very simple comparison function. In principle, the idea is to consider the matrix as a binary number (after smoothing into a vector) and sort based on the value of this number. This can be done as follows:

for(unsigned int j = 0; j < maxJ; j++)
{
  for(unsigned int i = 0; i < maxI; i++)
  {
    if(matrix1(i,j) < matrix2(i,j) return true;
    else if(matrix1(i,j) > matrix2(i,j) return false;
  }
}
return false;

However, this is inefficient due to sparseness of matrices, and I would like to use iterators for the same result. The algorithm using iterators seems simple, i.e. 1) take the first nonzero cell in each matrix, 2) compare j * maxJ + i for both, 3) if they are equal, take the following nonzero cells in each matrix and repeat. Unfortunately, in the code, this is very tedious, and I'm worried about errors.

, (a) , () " " ? , , .

.

-

, , , , , . , , . - , , . , - .

typedef boost::numeric::ublas::mapped_matrix<bool>::const_iterator1 iter1;
typedef boost::numeric::ublas::mapped_matrix<bool>::const_iterator2 iter2;

// Grabs the next nonzero cell in a sparse matrix after the cell pointed to by i1, i2.
std::pair<iter1, iter2> next_cell(iter1 i1, iter2 i2, iter1 end) const
{
    if(i2 == i1.end())
    {
        if (i1 == end)
            return std::pair<iter1, iter2>(i1, i2);
        ++i1;
        i2 = i1.begin();
    }
    else
    {
        ++i2;
    }

    for(; i1 != end;)
    {
        for(; i2 != i1.end(); ++i2)
        {
            return std::pair<iter1, iter2>(i1,i2);
        }
        ++i1;
        if(i1 != end) i2 = i1.begin();
    }
    return std::pair<iter1, iter2>(i1, i2);
}
+3
3

, .

, ,

declare list of sparse matrices ListA
declare map MatMAp with a sparse Matrix type mapping to a double, along with a
`StrictWeakMatrixOrderer` function which takes two sparse matrices.

Insert ListA into MatMap. 

: StrictWeakMatrixOrderer?

. ....


flatten() , ( ). flatten() , ( ) ( , /).

10 ^ 6. - " " . , .

, - , , , , .

" " " ". , .

" ", aka . ( foreach, , 1). O (n):

for i = 0 to max.
  if(a[i] != b[i])
     distance++

return distance

d(a,b) = d(b,a)
d(a,a) = 0
d(x, z) <= d(x, y) + d(y, z) 

, ....

  • 10^6 ( ).
  • O(n) .
    • O(n) . O(m), O(n*(n+n)) = O(n^2). , have < O(n). , std::vector [] " " SGI STL.
  • k*2*10^6, k - , , , .
+1

(a) , , , , ( ):

matrix3 = element_prod (matrix1, matrix2);

:

0 (false) * 1 (true) = 0 (false)
0*0 = 0
1*1 = 1

, 3 :)

0

, , boost:: sparse_matrix, , ( ) - , ( /).

, boost ( ). , / BLAS. , , , , .

Your question could be reformulated as follows: How can I effectively sort astronomically large numbers represented by a 2d bitmap (n = 100, so 100x100 elements will give you a number like 2 ^ 10000).

Good question!

0
source

Source: https://habr.com/ru/post/1716005/


All Articles