c++ - Eigen不同方法(LDLT、​​SVD、QR)同一个矩阵的不同解

标签 c++ matrix eigen

我试图理解为什么 Eigen::SVD、LDLT 和 QR 为同一个矩阵提供不同的解决方案?我的代码非常简单,非常感谢您的意见。 非常感谢您。

结果:

************************
Polynomial fit for power of 4 :
ldlt() solution:
-0.000267566
-0.000208661
 0.118686
-1.06809
 4.2021
SVD solution:
-0.00324908
 0.0892368
-0.713157
 1.46619
 2.41319
QR solution:
-0.00152415
 0.0374888
-0.2319
      0
 3.44815
hand-made solution:
 0.00447083
-0.131592
 1.51172
-5.22656
 7.11719
************************

代码:

double basic_function_(double x)
{
  return sin(x / 5) * exp(x / 10) + 5 * exp(-x / 2);
}

int main(){
vector<double> x, y;
int power = 4;
x = {1.0, 4.0, 10.0, 15.0};

for (int i = 0; i < power; ++i)
    y.push_back(basic_function_(x[i]));

//matrix size after basic logic confirmation (skipped)
unsigned int matrix_size_ = power;

//initializing f(x) vector and Matrix of x's
Eigen::VectorXd temp_y_ = Eigen::VectorXd::Map(&y[0], y.size());
Eigen::MatrixXd X(matrix_size_, matrix_size_+1);

for (int i = 0; i < matrix_size_; ++i)
    for (int j = 0; j <= matrix_size_; ++j)
        X(i, j) = pow(x[i], (matrix_size_ - j) );

//different solutions
//solution 1
Eigen::VectorXd a = (X.transpose() * X).ldlt().solve(X.transpose() * temp_y_);

//solution 2 (SVD)
Eigen::VectorXd a1 = X.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(temp_y_);

//Solution 3
Eigen::VectorXd a2 = X.colPivHouseholderQr().solve(temp_y_);

//Solution 4 (actually, solution 1, but simply hand-made)
Eigen::MatrixXd LHS_temp_, RHS_temp_, a3;
LHS_temp_ = X.transpose() * X;
LHS_temp_ = LHS_temp_.inverse();
RHS_temp_ = X.transpose() * temp_y_;
a3 = LHS_temp_ * RHS_temp_;

cout << " ************************ " << endl;
cout << "Polynomial fit for power of " << matrix_size_<< " :" << endl;
cout << "ldlt() solution:\n" << a <<  endl;
cout << "SVD solution:\n" << a1 << endl;
cout << "QR solution:\n" << a2 << endl;
cout << "hand-made solution:\n" << a3 << endl;
cout << " ************************ " << endl << endl;

return 0;
}

最佳答案

您有 4 个数据点,并用 4 次多项式(即 5 个自由度)对它们进行拟合。这意味着,剩下一个自由度,即解决方案不是唯一的。所有解决方案都非常适合数据点。

关于c++ - Eigen不同方法(LDLT、​​SVD、QR)同一个矩阵的不同解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43192314/

相关文章:

c++ - 运算符的初始化列表和 RHS

c++ - 如何在类中声明结构?

c++ - 使用已删除的 shared_ptr 中的原始指针的未定义行为?

c - C 矩阵的内存是否连续?

arrays - 如何在 Smalltalk 中访问二维数组中的元素

c++ - 四元数是非常相似旋转的翻转符号吗?

c++ - Eigen 模板函数和维度

c++ - 如何判断 Windows XP 后的操作系统是否没有默认文件扩展名关联?

python - 为什么 Matlab 矩阵求逆比 numpy 快?

package - 将依赖于 RcppEigen 的 R 包与 Microsoft R Open 中的 MKL 链接