Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a Eigen matrix be written to file in CSV format?

Suppose I have a double Eigen matrix and I want to write it to a csv file. I find the way of writing into a file in raw format but I need commas between entries. Here is the code I foudn for simple writing.

void writeToCSVfile(string name, MatrixXd matrix)
{
  ofstream file(name.c_str());
  if (file.is_open())
  {
    file << matrix << '\n';
    //file << "m" << '\n' <<  colm(matrix) << '\n';
  }
}
like image 804
erogol Avatar asked Aug 23 '13 10:08

erogol


3 Answers

Using format is a bit more concise:

// 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);
 }
like image 134
Partha Lal Avatar answered Oct 03 '22 02:10

Partha Lal


Here is what I came up;

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';
  }
}
like image 22
erogol Avatar answered Oct 03 '22 00:10

erogol


This is the MWE to the solution given by Partha Lal.

// 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);

}

Compile with g++ eigen2csv.cpp -I<EigenIncludePath>.

like image 22
JonasMu Avatar answered Oct 03 '22 02:10

JonasMu