其他分享
首页 > 其他分享> > Eigen库学习笔记(十一)读写矩阵文件

Eigen库学习笔记(十一)读写矩阵文件

作者:互联网

Eigen库学习笔记(十一)读写矩阵文件

由于调试时看不到矩阵的尺寸和数值,所以可以通过保存文件的形式查看矩阵。

1、写txt文件

代码:

void test_save_txt(Eigen::MatrixXf mat, string filename)
{
	ofstream outfile(filename, ios::trunc);
	outfile << mat;
	outfile.close();
}

测试用例

Eigen::MatrixXf mat(24, 3);
	mat <<
		50, 25, 25,
		100, 50, 50,
		150, 75, 75,
		75, 50, 50,
		150, 100, 100,
		225, 150, 150,
		100, 75, 50,
		200, 150, 100,
		300, 225, 150,
		100, 75, 75,
		200, 150, 150,
		300, 225, 225,
		425, 50, 75,
		850, 100, 150,
		1275, 150, 225,
		475, 75, 125,
		950, 150, 250,
		1425, 225, 375,
		400, 75, 75,
		800, 150, 150,
		1200, 225, 225,
		425, 75, 100,
		850, 150, 200,
		1275, 225, 300;

test_save_txt(mat, "data.txt");

输出到文件中的内容:

  50   25   25
 100   50   50
 150   75   75
  75   50   50
 150  100  100
 225  150  150
 100   75   50
 200  150  100
 300  225  150
 100   75   75
 200  150  150
 300  225  225
 425   50   75
 850  100  150
1275  150  225
 475   75  125
 950  150  250
1425  225  375
 400   75   75
 800  150  150
1200  225  225
 425   75  100
 850  150  200
1275  225  300

2、读写的一些选项

ofstream流,

ifstream流,

fstream流,默认是ios::in,所以如果没有文件,ios::app和ios::ate都是失败,

可见:ios::app不能用来打开输入流,即不能和ios::in相配合
而ios::ate可以和ios::in配合,此时定位到文件尾;如果没有ios::in相配合而只是同ios::out配合,那么将清空原文件
(ios::ate|ios::in–>在原文件尾追加内容;ios::ate—>清空原文件,ios::out是默认必带的,可加上也可不加,对程序无影响)

标签:150,ate,Eigen,文件,矩阵,读写,ios,75,out
来源: https://blog.csdn.net/juluwangriyue/article/details/122283958