C ++ Eigen:通过引用将矩阵的列传递给函数

问题描述 投票:1回答:1

我在C ++中使用Eigen创建了一个矩阵,我希望通过引用将该矩阵的一列传递给一个函数,我希望在不创建任何新内容的情况下修改该列。

这是我的示例代码

int changeTwo(Eigen::Ref<Eigen::ArrayXd> f) {
    for (int i = 0; i < 10; i++) {
      f(i) = 2;
    }
}

在上面的代码片段中,f将是矩阵的一列,我希望将该列的前10个元素更改为2.例如,我希望执行如下函数:

int main(int argc, const char * argv[]) {

  Eigen::MatrixXd randomMat = Eigen::MatrixXd::Random(1000,2);
  changeTwo(randomMat.col(0));
}

但是我收到此错误:

note: this candidate was rejected because at least one template argument could not be deduced

我试过像这样传递列:changeTwo(randomMat.col(0).array());,但是产生了同样的错误。

我可以得到一个关于出了什么问题的提示吗?

c++ eigen
1个回答
1
投票

我刚刚下载并设置了我的IDE的Eigen:运行Win7 64bit的Intel Quad Core Extreme上的MS Visual Studio 2017 CE。我将其编译为x86版本。我无法重现同样的错误:我与Henri Menke达成了协议。我能够编译并运行它没有错误,这是我的代码:

#include <iostream>
#include <fstream>

#include <Eigen/Eigen> // force to include full lib

using Eigen::MatrixXd;

void changeTwo( Eigen::Ref<Eigen::ArrayXd> f ) {
    for ( int i = 0; i < 10; i++ ) {
        f( i ) = 2;
    }
}

int main() {
    std::ofstream out;

    Eigen::MatrixXd randomMat = Eigen::MatrixXd::Random( 20, 2 );
    std::cout << randomMat << std::endl;
    std::cout << std::endl;

    out.open( "EigenResults.txt" );
    out << randomMat << std::endl;
    out << std::endl;

    changeTwo( randomMat.col( 0 ) );
    std::cout << randomMat << std::endl;
    out << randomMat << std::endl;

    out.close();

    std::cout << "\nPress any key and enter to quit." << std::endl;
    char q;
    std::cin >> q;

    return 0; 
}

输出: - 来自console&EigenResults.txt

 -0.997497    0.97705
  0.127171  -0.108615
 -0.613392  -0.761834
  0.617481  -0.990661
  0.170019  -0.982177
-0.0402539   -0.24424
 -0.299417  0.0633259
  0.791925   0.142369
   0.64568   0.203528
   0.49321   0.214331
 -0.651784  -0.667531
  0.717887    0.32609
  0.421003 -0.0984222
 0.0270699  -0.295755
  -0.39201  -0.885922
 -0.970031   0.215369
 -0.817194   0.566637
 -0.271096   0.605213
 -0.705374  0.0397656
 -0.668203    -0.3961

         2    0.97705
         2  -0.108615
         2  -0.761834
         2  -0.990661
         2  -0.982177
         2   -0.24424
         2  0.0633259
         2   0.142369
         2   0.203528
         2   0.214331
 -0.651784  -0.667531
  0.717887    0.32609
  0.421003 -0.0984222
 0.0270699  -0.295755
  -0.39201  -0.885922
 -0.970031   0.215369
 -0.817194   0.566637
 -0.271096   0.605213
 -0.705374  0.0397656
 -0.668203    -0.3961 
© www.soinside.com 2019 - 2024. All rights reserved.