其他分享
首页 > 其他分享> > Math(2)---Eigen修改稀疏矩阵中的值

Math(2)---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;
}

标签:存储,Eigen,矩阵,稀疏,CCS,---,非零,Math
来源: https://www.cnblogs.com/xuelanga000/p/13624657.html