2017-04-03 110 views
0

更新:yar的回答完美解釋。本徵不同方法(LDLT,SVD,QR)針對同一個矩陣的不同解法

來源: 我試圖理解爲什麼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; 
} 

回答

2

你有4個數據點和與度4(即5個自由度)一個polinomial適合他們。這意味着,剩下一個自由度,即解決方案不是唯一的。所有解決方案都完美地適合數據點。

+0

其中,SVD給你一個最小的L2範數。 – ggael

+0

Yikes !!!非常感謝 ) –

0

非常感謝yar。 沒有問題,只是爲了匹配數據點和自由度。我的錯。

相關問題