一杯清酒邀明月
天下本无事,庸人扰之而烦耳。

用Eigen库解Ax=b线性方程,使用最小二乘法

 1 #include <iostream>
 2  
 3 #include <Eigen/Dense>
 4  
 5 using namespace std;
 6  
 7 using namespace Eigen;
 8  
 9 int main()
10  
11 {
12  
13     //对方程Ax=b
14  
15  
16     MatrixXf A = MatrixXf::Random(3, 2);
17  
18     std::cout << "Here is the matrix A:\n" << A << std::endl;
19  
20     VectorXf b = VectorXf::Random(3);
21  
22     std::cout << "Here is the right hand side b:\n" << b << std::endl;
23  
24     cout << endl;
25  
26     cout << endl;
27  
28     cout << "**********jacobiSvd方法********************" << endl;
29  
30     MatrixXf x_jacobiSvd, x_colPivHouseholderQr;
31  
32     //jacobiSvd 方式:Slow (but fast for small matrices)
33  
34     x_jacobiSvd = A.jacobiSvd(ComputeThinU | ComputeThinV).solve(b);
35  
36     std::cout << "The least-squares solution is:\n"
37  
38         << A.jacobiSvd(ComputeThinU | ComputeThinV).solve(b) << std::endl;
39  
40  
41     cout << endl;
42  
43     cout << endl;
44  
45     cout << "**********colPivHouseholderQr方法********************" << endl;
46  
47     x_colPivHouseholderQr = A.colPivHouseholderQr().solve(b);
48  
49     //colPivHouseholderQr方法:fast
50  
51     std::cout << "The least-squares solution is:\n"
52  
53         << x_colPivHouseholderQr << std::endl;
54  
55  
56    
57  
58     system("pause");
59  
60     return 0;
61  
62  
63 }

 

posted on 2022-07-06 15:36  一杯清酒邀明月  阅读(562)  评论(0编辑  收藏  举报