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

3

7

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';
  }
}
Underbrush answered 23/8, 2013 at 10:30 Comment(0)
A
15

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);
 }
Amphithecium answered 9/5, 2014 at 14:21 Comment(1)
Don't you have to close the file? @ParthaLalLehmbruck
U
2

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';
  }
}
Underbrush answered 23/8, 2013 at 10:56 Comment(1)
Total C++ noob here. Was able to get this to work for me. I did have to make a couple tweaks though (which should be viewed with suspicion). Had to replace 'lexical_cast<std::string>' with 'std::to_string' to get it to compile. Had to close the file 'file.close();' to get the last line of the matrix to write to file.Sexed
B
2

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>.

Butyraldehyde answered 10/3, 2021 at 8:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.