【问题标题】:Looping over the non-zero elements of a uBlas sparse matrix循环遍历 uBlas 稀疏矩阵的非零元素
【发布时间】:2009-11-25 09:18:51
【问题描述】:

我有以下包含O(N) 元素的稀疏矩阵

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

我可以编写一个蛮力双循环来遍历O(N^2) 时间中的所有条目,如下所示,但这会太慢。

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

我怎样才能只循环O(N) 时间中的非零条目?对于每个非零元素,我想访问它的值和索引i,j

【问题讨论】:

    标签: c++ boost sparse-matrix ublas


    【解决方案1】:

    您可以在此常见问题解答中找到答案:How to iterate over all non zero elements?

    在你的情况下是:

    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;
      }
    }
    

    【讨论】:

    • 我忘了补充的重要说明:您为压缩矩阵选择的存储组织类型很重要,因为它决定了迭代压缩矩阵的最快方式是什么。如果你有 row_major 作为存储类型,我上面的例子是最快的迭代方式。如果选择 column_major,则必须交换内循环和外循环,即先循环列将是最快的。
    • boost 将根据存储表示(row-major 或 col-major)进行迭代。因此,上述相同的循环适用于任何一种表示形式。无需进行任何更改。
    • 很抱歉撞了一个旧帖子。我不确定这段代码是否真的有效,请参阅lists.boost.org/MailArchives/ublas/2006/11/1516.php。根据我的经验,它将遍历每个元素。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多