稀疏矩阵非零元素的修改
- 1.稀疏矩阵CCS存储中会用一块连续的内存空间,存储非零元素
- 2.稀疏矩阵CCS格式中,还会有两块区域
a.一块用来存储行下标
b.一块用来存储非零元素的偏移量 - 3.利用Eigen库函数函数找到这些内存空间的指针,就可以实现元素值的修改
示例:
#include <iostream>
#include <Eigen/Sparse>
using namespace std;
using namespace Eigen;
int main()
{
SparseMatrix<double> mat(5, 5); //默认CCS格式
MatrixXd Dmat(5, 5);
Dmat << 0, 3, 0, 0, 0,
22, 0, 0, 0, 17,
7, 5, 0, 1, 0,
0, 0, 0, 0, 0,
0, 0, 14, 0, 8;
mat = Dmat.sparseView();
std::cout << "Dense Matrix" << std::endl;
std::cout << Dmat << std::endl;
std::cout << "--------------------" << std::endl;
std::cout << "sparse Matrix" << std::endl;
std::cout << mat.innerSize() << std::endl; //3
std::cout << mat.outerSize() << std::endl; //3
std::cout << mat.nonZeros() << std::endl; //2
std::cout << mat << std::endl;
std::cout << "value" << mat.valuePtr()[0] << std::endl;
std::cout << "value" << mat.valuePtr()[1] << std::endl;
for (int i = 0; i < mat.innerSize(); ++i) //打印稀疏矩阵非零元素的行索引
{
std::cout << "innerIndexPtr=" << mat.innerIndexPtr()[i] << std::endl;
}
for (int i = 0; i < mat.outerSize(); ++i) //打印稀疏矩阵非零元素的偏移值
{
std::cout << "outerIndexPtr=" << mat.innerIndexPtr()[i] << std::endl;
}
std::cout << "-------修改后-------------" << std::endl;
(mat.valuePtr())[0] = 4; //修改第一个非零元素的值
cout << mat << endl;
}