user189035
user189035

Reputation: 5789

write matrix to file in eigen?

I am trying to learn C++ with the Eigen library.

int main(){
    MatrixXf m = MatrixXf::Random(30,3);
    cout << "Here is the matrix m:\n" << m << endl;
    cout << "m" << endl <<  colm(m) << endl;
    return 0;
}

How can I export m to a text file (I have searched the documentations and have not found mention of an writing function)?

Upvotes: 17

Views: 27617

Answers (2)

Djul77
Djul77

Reputation: 37

I wrote this function:

    void get_EigentoData(MatrixXf& src, char* pathAndName)
    {
          ofstream fichier(pathAndName, ios::out | ios::trunc);  
          if(fichier)  // si l'ouverture a réussi
          {   
            // instructions
            fichier << "Here is the matrix src:\n" << src << "\n";
            fichier.close();  // on referme le fichier
          }
          else  // sinon
          {
            cerr << "Erreur à l'ouverture !" << endl;
          }
     }

Upvotes: 2

cooky451
cooky451

Reputation: 3510

If you can write it on cout, it works for any std::ostream:

#include <fstream>

int main()
{
  std::ofstream file("test.txt");
  if (file.is_open())
  {
    MatrixXf m = MatrixXf::Random(30,3);
    file << "Here is the matrix m:\n" << m << '\n';
    file << "m" << '\n' <<  colm(m) << '\n';
  }
}

Upvotes: 20

Related Questions