特征库 - >使用来自文件或现有std :: vector <string>内容的数据初始化矩阵(c ++)

die*_*ste 14 c++ file vector matrix eigen

我的问题是如何初始化一个特征矩阵,但不是这样:

matrix << 1,0,1,0,
          1,0,1,0,
          1,0,1,0,
Run Code Online (Sandbox Code Playgroud)

我有一个矩阵,看起来像上面的一个(逗号或没有逗号无关紧要)存储在txt文件中.

我已经编写了一个函数来读取每一行并将其放入一个向量中,现在我想用这个数据创建一个矩阵

但它不起作用,我找不到任何解释如何在不编写值的情况下将数据分配给矩阵的页面.(如上例所示)

我需要的只是我的文件中的一个特征矩阵的数据

到目前为止我尝试了什么:(PS:有迭代器的想法,但我想用真正的大矩阵需要太长时间,我只是用1-2维矩阵试过这个例子)

int readFromFile (const char * path, vector <string> & mv)
{
    fstream file;
    string line;
    file.open(path);

    while (getline(file,line))
    {
        mv.push_back(line);
    }
    file.close();
    return 0;
}


typedef Matrix <int, 1, 2> MyMatrix;

int fromVectoEigen (vector<string> & source, MyMatrix & target)
{   //for (int i = source.size(); i<0 ; i--)
    //{

        string valuerow = source.back();
        string::iterator it = valuerow.begin();
        target.row(0)<< *it;
        target.row(0)<<*it+1;
        //source.pop_back();
    //}

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,只是说Matrix.row(i) = vector.back()不起作用.

lac*_*cal 6

以下代码适用于包含任意大小矩阵的文件:

#include <iostream>
#include <fstream>
#include <string>
#include <Eigen/Dense>

using namespace std;
using namespace Eigen;

#define MAXBUFSIZE  ((int) 1e6)

MatrixXd readMatrix(const char *filename)
    {
    int cols = 0, rows = 0;
    double buff[MAXBUFSIZE];

    // Read numbers from file into buffer.
    ifstream infile;
    infile.open(filename);
    while (! infile.eof())
        {
        string line;
        getline(infile, line);

        int temp_cols = 0;
        stringstream stream(line);
        while(! stream.eof())
            stream >> buff[cols*rows+temp_cols++];

        if (temp_cols == 0)
            continue;

        if (cols == 0)
            cols = temp_cols;

        rows++;
        }

    infile.close();

    rows--;

    // Populate matrix with numbers.
    MatrixXd result(rows,cols);
    for (int i = 0; i < rows; i++)
        for (int j = 0; j < cols; j++)
            result(i,j) = buff[ cols*i+j ];

    return result;
    };
Run Code Online (Sandbox Code Playgroud)

问候。


小智 5

我刚刚发布了一个 Eigen 包的扩展,它可以做一些你想要的。它定义了 >> 运算符,因此您可以说:

矩阵Xd A(5,5); cin >> A;

它还允许您将 VectorXd 分配为等于 std::vector。可以在此处找到 Eigen 的扩展版本。但是,它(还)不允许您将 std::vector 复制到不是矢量的 MatrixXd 对象中。您想要的功能是 Eigen 中的 Map 函数。