6

假设我有一个双特征矩阵,我想将它写入一个 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';
  }
}
4

3 回答 3

14

使用format更简洁一些:

// define the format you want, you only need one instance of this...
const static IOFormat CSVFormat(StreamPrecision, DontAlignCols, ", ", "\n");

...

void writeToCSVfile(string name, MatrixXd matrix)
{
    ofstream file(name.c_str());
    file << matrix.format(CSVFormat);
 }
于 2014-05-09T14:21:18.337 回答
2

这就是我想出的;

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';
  }
}
于 2013-08-23T10:56:34.807 回答
1

这是Partha Lal给出的解决方案的 MWE 。

// eigen2csv.cpp

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

// define the format you want, you only need one instance of this...
// see https://eigen.tuxfamily.org/dox/structEigen_1_1IOFormat.html
const static Eigen::IOFormat CSVFormat(Eigen::StreamPrecision, Eigen::DontAlignCols, ", ", "\n");

// writing functions taking Eigen types as parameters, 
// see https://eigen.tuxfamily.org/dox/TopicFunctionTakingEigenTypes.html
template <typename Derived>
void writeToCSVfile(std::string name, const Eigen::MatrixBase<Derived>& matrix)
{
    std::ofstream file(name.c_str());
    file << matrix.format(CSVFormat);
    // file.close() is not necessary, 
    // desctructur closes file, see https://en.cppreference.com/w/cpp/io/basic_ofstream
}

int main()
{
    Eigen::MatrixXd vals = Eigen::MatrixXd::Random(10, 3);
    writeToCSVfile("test.csv", vals);

}

用 编译g++ eigen2csv.cpp -I<EigenIncludePath>

于 2021-03-10T08:05:45.153 回答