如何将特征矩阵以CSV格式写入文件?

时间:2013-08-23 10:30:44

标签: 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';
  }
}

3 个答案:

答案 0 :(得分:11)

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

答案 1 :(得分: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';
  }
}

答案 2 :(得分:0)

这是 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> 编译。