我正在尝试将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();
}
这将生成所需的按行输出。