【问题标题】:How can a Eigen matrix be written to file in CSV format?如何将特征矩阵以 CSV 格式写入文件?
【发布时间】:2013-08-26 08:57:27
【问题描述】:

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

【问题讨论】:

    标签: csv file-io matrix eigen


    【解决方案1】:

    使用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);
     }
    

    【讨论】:

    • 不需要关闭文件吗? @ParthaLal
    【解决方案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';
      }
    }
    

    【讨论】:

    • 这里的总 C++ 菜鸟。能够让它为我工作。不过,我确实必须进行一些调整(应该怀疑)。必须将 'lexical_cast<:string>' 替换为 'std::to_string' 才能编译。不得不关闭文件'file.close();'获取要写入文件的矩阵的最后一行。
    【解决方案3】:

    这是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&lt;EigenIncludePath&gt;编译。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-16
      • 1970-01-01
      • 2023-03-17
      • 2018-05-07
      • 1970-01-01
      相关资源
      最近更新 更多