[Eigen]Eigen将矩阵写至文件与读文件的简单例子

代码

#include <iostream>
#include <vector>
#include <Eigen/Dense>
#include <fstream>

void ReadData(std::istream &fin, Eigen::MatrixXd &m_matrix)
{
	int numRow = m_matrix.rows();
	int numCol = m_matrix.cols();

	Eigen::VectorXd vecPerRow(numRow);
	for (int j = 0; j < numRow; j++)//共numRow行
	{
		for (int i = 0; i < numCol; i++)//共numCol列组成一行
		{
			fin >> m_matrix(j, i);
		}
		
	}	
}
//blog.csdn.net/xinshuwei/article/details/94064790

int main()
{
	Eigen::MatrixXd m_matrix, m_matrixRead;
	m_matrix.resize(4, 3);
	m_matrix.fill(0);
	m_matrixRead.resize(4, 3);
	std::cout << m_matrix << std::endl;

	/*写文件**/
	std::ofstream fout("matrixTest.bin", std::ios::binary);
	fout << m_matrix << std::endl;
	fout.flush();
	//Eigen::VectorXd vecPerRow(4);
	//std::cout << vecPerRow << std::endl;

	/*读文件**/
	std::ifstream fin("matrixTest.bin", std::ios::binary);
	if (!fin)
	{
		return 0;
	}
	
	ReadData(fin, m_matrixRead);
	std::cout <<"Matrix read from file:\n"<< m_matrixRead << std::endl;
	
	return 0;
}

要点

  • Eigen重载了操作符"<<",可以在iostream中直接打印矩阵
  • 也可以通过重载操作符">>"达到iostream读文件中的矩阵进入
  • 写的时候好像是按列写入的,读好像是按行读取的,具体机制没有深究
  • 5
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值