如何将std::vector转换为Eigen中的矩阵? 我对堆栈溢出和C++有点新,因此可以自由地纠正代码中的任何错误和这个问题的格式。

如何将std::vector转换为Eigen中的矩阵? 我对堆栈溢出和C++有点新,因此可以自由地纠正代码中的任何错误和这个问题的格式。,c++,c++11,matrix,vector,eigen,C++,C++11,Matrix,Vector,Eigen,我正在尝试使用正规方程制作一个线性回归计算器,它涉及矩阵的转置和向量(及其逆)的乘法。程序应该从csv文件中读取信息,并将该文件中的信息传递到矩阵中,然后计算回归线。为了使这项工作更容易,我决定使用一个名为Eigen的库进行矩阵乘法 我遇到的问题是,Map函数只能接受数组,而不是std::vector 这就是我到目前为止所做的: float feature_data[] = { 1, 1, 1, 1, 1, 1, 2, 4.5, 3, 1,4,

我正在尝试使用正规方程制作一个线性回归计算器,它涉及矩阵的转置和向量(及其逆)的乘法。程序应该从csv文件中读取信息,并将该文件中的信息传递到矩阵中,然后计算回归线。为了使这项工作更容易,我决定使用一个名为Eigen的库进行矩阵乘法

我遇到的问题是,
Map
函数只能接受数组,而不是std::vector

这就是我到目前为止所做的:

float feature_data[] = { 1, 1, 1, 1, 1, 1,
                         2, 4.5, 3, 1,4, 5};
float labels[] = { 1, 4, 3, 2, 5, 7 };


//maps the array to a matrix called "feature_data"
MatrixXf mFeatures = Map< Matrix<float, 6, 2> >(feature_data);
MatrixXf mLabels = Map< Matrix<float, 6, 1> >(labels);

//use the toArray function
std::vector<float> test_vector = { 2,1,3 };
float* test_array = toArray(test_vector);


calcLinReg(mFeatures, mLabels);

const int n = 2;
int arr[n];

system("pause");
float-feature_-data[]={1,1,1,1,1,
2, 4.5, 3, 1,4, 5};
浮动标签[]={1,4,3,2,5,7};
//将数组映射到名为“feature_data”的矩阵
MatrixF mFeatures=地图<矩阵>(要素数据);
MatrixXf mLabels=Map(标签);
//使用toArray函数
std::vector test_vector={2,1,3};
浮点*测试数组=toArray(测试向量);
calcLinReg(mFeatures,mLabels);
常数int n=2;
int-arr[n];
系统(“暂停”);
在上下文中,toArray函数是我从向量生成数组的失败尝试(老实说,它可以工作,但它返回的指针不能传递到Eigen中的
Map
函数中。)
calcLinReg
完全按照其听起来的方式执行:计算线性回归线参数


我可以把向量转换成数组,或者把向量转换成矩阵吗

尝试使用向量怎么样,这样可以访问向量内部使用的内存数组,如下所示:

    std::vector<float> test_vector = { 2,1,3 };
    float* test_array = test_vector.data();
    Eigen::MatrixXf test = Eigen::Map<Eigen::Matrix<float, 3, 1> >(test_array);
std::vector test_vector={2,1,3};
float*test_数组=test_vector.data();
特征::矩阵XXF测试=特征::映射(测试数组);
或更短:

    std::vector<float> test_vector = { 2,1,3 };
    Eigen::MatrixXf test = Eigen::Map<Eigen::Matrix<float, 3, 1> >(test_vector.data());
std::vector test_vector={2,1,3};
特征::矩阵xxf test=特征::映射(test_vector.data());
注意asignment实际上复制了数据,因此这是安全的。但是,您也可以像这样直接使用向量的数据

    std::vector<float> test_vector(3,2);
    Eigen::Map<Eigen::Matrix<float, 3, 1> > dangerousVec (test_vector.data());
std::vector test_vector(3,2);
特征::映射危险向量(test_vector.data());

如果vector超出范围,内存将被释放,dangerousVec的数据将处于危险状态。

这似乎工作正常,但我不认为Map函数可以接收指针。如果行和列数是动态的,例如dosent编译的Eigen::Map,我们如何实现这一点