ero*_*gol 5 csv file-io matrix eigen
假设我有一个双特征矩阵,我想将它写入csv文件.我找到了以原始格式写入文件的方法,但我需要在条目之间使用逗号.这是我为简单写作而编写的代码.
void writeToCSVfile(string name, MatrixXd matrix)
{
ofstream file(name.c_str());
if (file.is_open())
{
file << matrix << '\n';
//file << "m" << '\n' << colm(matrix) << '\n';
}
}
Run Code Online (Sandbox Code Playgroud)
Par*_*Lal 11
使用format更简洁:
// define the format you want, you only need one instance of this...
const static IOFormat CSVFormat(StreamPrecision, DontAlignCols, ", ", "\n");
Run Code Online (Sandbox Code Playgroud)
...
void writeToCSVfile(string name, MatrixXd matrix)
{
ofstream file(name.c_str());
file << matrix.format(CSVFormat);
}
Run Code Online (Sandbox Code Playgroud)
这就是我的想法;
void writeToCSVfile(string name, MatrixXd matrix)
{
ofstream file(name.c_str());
for(int i = 0; i < matrix.rows(); i++){
for(int j = 0; j < matrix.cols(); j++){
string str = lexical_cast<std::string>(matrix(i,j));
if(j+1 == matrix.cols()){
file<<str;
}else{
file<<str<<',';
}
}
file<<'\n';
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5529 次 |
| 最近记录: |