我想写一个 Eigen::VectorXd
到一个CSV文件。该向量来自于一个 Eigen::MatrixXd
. 我的函数定义如下。
void writeMatrixToCSVwithID(fs::path path, VectorXd row, unsigned long int row_id){
const static IOFormat CSVFormat(StreamPrecision, DontAlignCols, ", ", "\n");
ofstream file(path.c_str(), std::ofstream::out | std::ofstream::app);
row.resize(1, row.size());
file << row_id << ", " << row.format(CSVFormat) << std::endl;
file.close();
}
问题是这个函数生成的文件是:
11, 0.247795
0.327012
0.502336
0.569316
0.705254
12, 0.247795
0.327012
0.502336
0.569316
0.705254
预期的输出是:
11, 0.247795, 0.327012, 0.502336, 0.569316, 0.705254
12, 0.247795, 0.327012, 0.502336, 0.569316, 0.705254
我需要改变什么?
错误的原因是Eigen将VectorXd作为一列输出。MatrixXd::row(id)
返回 Block
似乎输出的是行或列提取的列!这样一来,就不需要通过传球的方式,而是将行或列的提取作为一个列。
因此,与其将 VectorXd
行,我现在将该行作为一个 MatrixXd
. 该 IOFormat
对象初始化时,行分隔符为','。
void writeMatrixToCSVwithID(fs::path path, MatrixXd row, unsigned long int row_id){
const static IOFormat CSVFormat(StreamPrecision, DontAlignCols, ", ", ", ");
ofstream file(path.c_str(), std::ofstream::app);
row.resize(1, row.size()); // Making sure that we are dealing with a row.
file << row_id << ", " << row.format(CSVFormat) << std::endl;
file.close();
}
这样就会产生所需的按行分类的输出。