如何在Eigen中将矩阵写入文件?

17

我正在尝试使用Eigen库学习C++。

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;
}

我该如何将m导出到文本文件中(我已查阅文档但没有找到写入函数的提及)?

2个回答

20

如果你可以用cout输出,那么它适用于任何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';
  }
}

11
colm() 函数应该做什么?但它对我没用。 - Ludi
colm()只是问题的背景,只需查看原始问题即可。 - hao li

2
我编写了这个函数:
    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;
          }
     }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接