【问题标题】:Eigen Sparse Matrix get Indices of Nonzero Elements特征稀疏矩阵获取非零元素的索引
【发布时间】:2015-03-04 12:33:40
【问题描述】:

我第一次使用特征稀疏矩阵,现在我想知道如何获取非零元素的索引。 我构造了我的稀疏矩阵如下:

Eigen::SparseMatrix<Eigen::ColMajor> Am(3,3);

通过查看 m_indices 变量,我可以在 VS 中看到一些索引。但我无法访问它们。谁能帮帮我吗? 对于像

这样的矩阵
( 1 0 1 
  0 1 1
  0 0 0 )

我希望索引类似于(0,0), (0,2), (1,1), (1,2)

有什么办法吗?

附:我的矩阵比 3x3 大得多。

【问题讨论】:

    标签: eigen sparse-matrix


    【解决方案1】:

    tutorial 的代码与此类似:

    for (int k=0; k < A.outerSize(); ++k)
    {
        for (SparseMatrix<int>::InnerIterator it(A,k); it; ++it)
        {
            std::cout << "(" << it.row() << ","; // row index
            std::cout << it.col() << ")\t"; // col index (here it is equal to k)
        }
    }
    

    【讨论】:

    • 您知道为什么这会给我一个错误,即 InnerIterator 是私有的吗? 'Eigen::SparseCompressedBase::InnerIterator::InnerIterator(const Eigen::SparseMatrixBase&, Eigen::Index) [with T = Eigen::SparseMatrix;派生 = Eigen::SparseMatrix; Eigen::Index = long int]' 在这个上下文中是私有的`?
    • 找出它给我这个错误的原因:我没有指定我想使用 RowMajor。使用 SparseMatrix&lt;int, Eigen::RowMajor&gt;::InnerIterator 代替工作!
    【解决方案2】:
    Eigen::SparseMatrix<int, Eigen::ColMajor> A(2,3);
    for (int k=0; k < A.outerSize(); ++k)
    {
        for (Eigen::SparseMatrix<int,Eigen::ColMajor>::InnerIterator it(A,k); it; ++it)
        {
            std::cout << "(" << it.row() << ","; // row index
            std::cout << it.col() << ")\t"; // col index (here it is equal to k)
        }
    }
    

    【讨论】:

    • 您好,欢迎来到 stackoverflow,感谢您的回答。您能否简单地解释一下您解决了什么问题以及您是如何解决的,而不是仅仅发布一段代码?这将有助于以后发现此问题的人更好地了解该问题以及如何处理它。
    【解决方案3】:

    使用 libigl 的igl::find,您可以将非零的索引提取到特征向量中:

    Eigen::VectorXi I,J;
    Eigen::VectorXd V;
    igl::find(Am,I,J,V);
    

    在您的示例中,这些将包含:

    I: 0 1 0 1
    J: 0 1 2 2
    V: 1 1 1 1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-25
      • 2013-03-28
      • 2017-11-16
      相关资源
      最近更新 更多