将特征矩阵转换为C++形式的三元组
Convert an Eigen matrix to Triplet form C++
我认为Eigen使用压缩方法来存储稀疏矩阵。有什么方法可以从std::vectors中提取特征稀疏矩阵的Triplet格式向量吗?
谢谢。
更多信息(三元组格式示例)矩阵的Triplet格式:
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
问题的答案是:
// 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中打开它,四处寻找指向数据数组的指针,并编写一个对运行时没有影响的复杂函数,因为矩阵是稀疏的,而复制在非零元素方面是线性的。
如教程所示:
#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 << "RowtColtVal" <<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;
}
相关文章:
- 如何有效地找到数组中三元组和的最小差异?
- 黑客兰克中的错误比较三元组代码
- 在C++中生成字母的三元组
- 特征用三元组填充稀疏行主矩阵
- 求数组中三元组 (i, j, k) 的数量,使得 A[i] + A[j] = 2 * A[k]
- 为什么在 Gnu gcc/g++ 中解析三元组序列的字符串文字?
- 使用欧几里得公式求全毕达哥拉斯三元组
- 所有毕达哥拉斯的三元组都小于500
- 来自三元组的稀疏矩阵
- 如何在C++中对三元组进行排序
- 在最小执行时间内找到给定数组中和为零的所有唯一三元组
- 在c++中查找数组中和等于零的所有唯一三元组
- 将特征矩阵转换为C++形式的三元组
- 无法推断编译器目标三元组
- 动态编程/记忆(计数三元组)
- 寻找毕达哥拉斯三元组:欧几里得公式
- 我的三角三元组程序有一个问题
- 计算勾股三元组
- 如何使用 Clang 的 C++ API 从文件名/行/列三元组中获取源位置
- 优化C++中的三元组求和