【问题标题】:Convert an Eigen matrix to Triplet form C++将特征矩阵转换为 C++ 形式的三元组
【发布时间】:2015-04-25 11:46:21
【问题描述】:

我认为 Eigen 使用压缩方法来存储稀疏矩阵。有什么方法可以从 std::vectors 中提取特征稀疏矩阵的三重格式向量?

谢谢。

更多信息(三连音格式示例) 矩阵的三元组格式:

A=
3 0 4 0
0 0 1 0
0 2 0 5
4 0 0 0

i = 1 1 2 3 3 4  // row
j = 1 3 3 2 4 1 // column
S = 3 4 1 2 5 4  // values

【问题讨论】:

    标签: c++ matrix eigen sparse-matrix triplet


    【解决方案1】:

    问题的答案,即:

    // Is there some method such as:
    
    std::vector<Eigen::Triplet<double>> T = SparseMat.to_triplets();
    
    // in Eigen?
    

    是没有,好像没有这样的功能。

    相反,

    std::vector<Eigen::Triplet<double>> to_triplets(Eigen::SparseMatrix<double> & M){
        std::vector<Eigen::Triplet<double>> v;
        for(int i = 0; i < M.outerSize(); i++)
            for(typename Eigen::SparseMatrix<double>::InnerIterator it(M,i); it; ++it)
                v.emplace_back(it.row(),it.col(),it.value());
        return v;
    }
    
    auto t = to_triplets(SparseMat);
    

    如果你想做得更快,在 IDE 中打开它,四处寻找指向数据数组的指针,然后编写一个不会影响运行时的卷积函数,因为矩阵是稀疏的,而复制是线性的就非零元素而言。

    【讨论】:

      【解决方案2】:

      只需如tutorial所示:

      #include <Eigen/Sparse>
      #include <iostream>
      
      using namespace Eigen;
      using std::cout;
      using std::endl;
      
      typedef Triplet<int> Trip;
      
      int main(int argc, char *argv[]){
      
          std::vector<Trip> trp, tmp;
      
          // I subtracted 1 from the indices so that the output matches your question
          trp.push_back(Trip(1-1,1-1,3));
          trp.push_back(Trip(1-1,3-1,4));
          trp.push_back(Trip(2-1,3-1,1));
          trp.push_back(Trip(3-1,2-1,2));
          trp.push_back(Trip(3-1,4-1,5));
          trp.push_back(Trip(4-1,1-1,4));
      
          int rows, cols;
          rows = cols = 4;
          SparseMatrix<int> A(rows,cols);
      
          A.setFromTriplets(trp.begin(), trp.end());
          cout << "Matrix from triplets:" << endl;
          cout << A << endl;            
      
          cout << endl << "Triplets:" << endl;
          cout << "Row\tCol\tVal" <<endl;
          for (int k=0; k < A.outerSize(); ++k)
          {
              for (SparseMatrix<int>::InnerIterator it(A,k); it; ++it)
              {
                  cout << 1+it.row() << "\t"; // row index
                  cout << 1+it.col() << "\t"; // col index (here it is equal to k)
                  cout << it.value() << endl;
              }
          }
      
          return 0;
      }
      

      【讨论】:

      • 感谢您的回复。但这是如何从三元组向量制作矩阵。我正在寻找“如何获取已经以 Eigen 格式存在的矩阵的三元组向量”。
      • @SinaJ 见第二部分。与其打印,不如构造三元组。
      • @SinaJ 如果要访问原始指针,可以通过m.valuePtr()m.outerIndexPtr()m.innerIndexPtr() 访问它们,但它们的长度不同(即不能天真地转换为三元组)。
      • @bordeo 我不关注。您是在问如何获取迭代器并在三元组构造函数中使用它们?
      猜你喜欢
      • 2012-01-16
      • 2019-08-14
      • 1970-01-01
      • 2015-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多