error: no matching function for call to 'conjugate_gradient' in Eigen Library

error: no matching function for call to 'conjugate_gradient' in Eigen Library

我在编译具有 Eigen 库的 C++ 代码时遇到以下错误

error: no matching function for call to 'conjugate_gradient' in Eigen Library

下面是代码:

SparseMatrix<double> A(truncatedSize,truncatedSize);
for(int i=0;i<truncatedSize;i++)
{
    for(int j=0;j<truncatedSize;j++)
    {
        A.insert(i,j)=TruncatedGlMatrix[i][j];
    }
}

VectorXf V(truncatedSize);
for(int i=0;i<truncatedSize;i++)
{       
    V(i)=TruncatedForce[i][1];
}

// solve Ax = b
ConjugateGradient<SparseMatrix<double>, Lower|Upper> cg;
cg.compute(A);

VectorXf xa(truncatedSize);
xa = cg.solve(V);

您确实需要将其显示为 MCVE。如果你再模拟一下,你的结果可能是这样的:

#include <Eigen/Core>
#include <Eigen/Sparse>

using namespace Eigen;

int main()
{
    int truncatedSize = 50;
    SparseMatrix<double> A(truncatedSize, truncatedSize);

//  We have no idea what TruncatedGlMatrix or TruncatedForce are...
//  for (int i = 0; i < truncatedSize; i++)
//  {
//      for (int j = 0; j < truncatedSize; j++)
//      {
//          A.insert(i, j) = TruncatedGlMatrix[i][j];
//      }
//  }

    VectorXf V(truncatedSize);
//  for (int i = 0; i < truncatedSize; i++)
//  {
//      V(i) = TruncatedForce[i][1];
//  }

    // solve Ax = b
    ConjugateGradient<SparseMatrix<double>, Lower | Upper> cg;
    cg.compute(A);

    VectorXf xa(truncatedSize);
    xa = cg.solve(V);
    return 0;
}

我从你那里得到了不同的错误,但这可能是因为我不得不对你实际看到的内容进行一些猜测。在上面的代码中,问题在于您混合了 doublefloat 标量类型。即,

xa = cg.solve(V);

xaVfloat 的向量,而 cgA 的标量类型是 double。您必须在这些之间显式转换,因此将该行替换为

xa = cg.solve(V.cast<double>()).cast<float>();

会解决我的 MCVE 的问题(这也可能是你的问题,我不太清楚)。