用Eigen库解Ax=b线性方程,使用最小二乘法
#include <iostream>
#include <Eigen/Dense>
using namespace std;
using namespace Eigen;
int main()
{
//对方程Ax=b
MatrixXf A = MatrixXf::Random(3, 2);
std::cout << "Here is the matrix A:\n" << A << std::endl;
VectorXf b = VectorXf::Random(3);
std::cout << "Here is the right hand side b:\n" << b << std::endl;
cout << endl;
cout << endl;
cout << "**********jacobiSvd方法********************" << endl;
MatrixXf x_jacobiSvd, x_colPivHouseholderQr;
//jacobiSvd 方式:Slow (but fast for small matrices)
x_jacobiSvd = A.jacobiSvd(ComputeThinU | ComputeThinV).solve(b);
std::cout << "The least-squares solution is:\n"
<< A.jacobiSvd(ComputeThinU | ComputeThinV).solve(b) << std::endl;
cout << endl;
cout << endl;
cout << "**********colPivHouseholderQr方法********************" << endl;
x_colPivHouseholderQr = A.colPivHouseholderQr().solve(b);
//colPivHouseholderQr方法:fast
std::cout << "The least-squares solution is:\n"
<< x_colPivHouseholderQr << std::endl;
system("pause");
return 0;
}