Eigen构造稀疏矩阵,这里我们对稀疏矩阵采用三元组的存储方式,即用(i,j,value(i,j))这样的组合把非零元的位置和值表示出来。废话不多说,我们直接上例子
#include "iostream"
#include "Eigen/SparseCore"
using namespace std;
using namespace Eigen;
int main()
//我们需要生成的矩阵
/****************
0 1 0 0 0
0 0 0 2 0
1 0 0 0 0
0 0 0 0 3
0 0 0 0 0
***************/
{
SparseMatrix<double> A(5,5);
vector < Triplet <double> >triplets;
// 初始化非零元位置,r表示行,c表示列,默认列优先。
int r[4]={2,0,1,3};
int c[4]={0,1,3,4};
double value[]={1,1,2,3}; //给非零元赋值
for (int i=0;i<4;i++)
triplets.emplace_back(r[i],c[i],value[i]);
//初始化矩阵
A.setFromTriplets (triplets.begin(),triplets.end());
cout <<"A="<<endl<<A<<endl;
}
输出结果
wanghai@de4f88556b1b:~/wanghai/build$ ./SMatrix
A=
Nonzero entries:
(1,2) (1,0) (2,1) (3,